这应该从底部显示的模型中提取一条记录,传递给 JavaScript 以显示在 UI 上。
我在提取 location
多个数据进行推送时遇到问题。这是因为它只拉取一项,而不是多对多关联的所有项目。
location
用于将标签放置在 select2 multiselect
上
当前不需要技能组
数据
def GetPersonnelData(request, res_id):
data = []
res = Resource.objects.get(id=res_id)
if not res: return HttpResponseNotFound()
role = list(Role.objects.values_list('role_name').filter(id=res.role_id))
emp = list(Employer.objects.values_list('employer_name').filter(id=res.employer_id))
teamz = list(Team.objects.values_list('team_name').filter(id=res.teams_id))
t = {
"title":res.title,
"pk":res.pk,
"last_name":res.last_name,
"preferred_name":res.preferred_name,
"employstatus":res.employstatus,
"employer":emp,
"business_phone":res.business_phone,
"mobile_phone":res.mobile_phone,
"email":res.email,
"teams":teamz,
"role_name":role,
"notes":res.notes,
"updated_by":res.updated_by,
"updated_on":res.updated_on,
}
data.append(t);
print data
loc = Resource.objects.get(pk=res_id)
for x in loc.location.all().filter(resource=res_id):
l = {
"location":x.name,
}
print x
Django 模型
class Resource(models.Model):
title = models.CharField(max_length=10)
preferred_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=30)
employer = models.ForeignKey('Employer')
employstatus = models.CharField(max_length=20)
role = models.ForeignKey('Role')
teams = models.ForeignKey('Team')
location = models.ManyToManyField('Location')
email = models.CharField(max_length=50, blank=True, null=True)
business_phone = models.CharField(max_length=15, blank=True, null=True)
mobile_phone = models.CharField(max_length=15, blank=True, null=True)
notes = models.CharField(max_length=200, blank=True, null=True)
updated_by = models.CharField(max_length=30, blank=True, null=True)
updated_on = models.DateTimeField(auto_now=True)
archived = models.BooleanField(default=False)
skillset = models.ManyToManyField('ReferenceSkillList')
最佳答案
如果您希望 print x
打印所有位置,您应该将缩进更改为 for block 内(现在在 for block 外,您应该收到未知名称错误)。就像这样:
for x in loc.location.all().filter(resource=res_id):
l = {
"location":x.name,
}
print x
如果你想将所有位置名称收集到字典中,你应该将其更改为:
l = {"location":[]}
for x in loc.location.all().filter(resource=res_id):
l["location"] += x.name
在循环的每次迭代中创建新字典之前,仅保留最后一次实例化的结果。
关于python - 只从 django Manytomany 中取出一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35278719/