首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在django中获取相关集合(多对多字段)

如何在django中获取相关集合(多对多字段)
EN

Stack Overflow用户
提问于 2018-07-12 02:32:56
回答 2查看 47关注 0票数 0

我有一个员工模型

class Employees(models.Model):
name = models.CharField(max_length=200, help_text="Enter the name of the employee")
location = models.ManyToManyField('Coverage')

def __str__(self):
    return self.name'

和一个位置模型

class Coverage(models.Model):
name = models.CharField(max_length=300, help_text="Enter employee location")
time_needed = models.IntegerField(help_text="Enter time needed to get to work. eg (40 = > 40 minutes)")

def __str__(self):
    return self.name

如何使用( employees = Employees.objects.all())从我的模板访问coverage - time_needed

我试过{{employees.location.time_needed}},但它不起作用。任何好的答案都将不胜感激。

ps :这只是一个更大的模型类的一小段

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-12 02:44:18

employees = Employees.objects.all()是一个查询集,您不能使用它访问字段。但是,如果您遍历它,您将能够访问每个实例,然后您将能够拥有任何实例的location。因为location是一个ManyToManyField location = models.ManyToManyField('Location')。您还需要遍历它。

{% for employee in employees %}
    {{ employee.location.all }} // Location queryset

    {% for location in employee.location.all %}
          {{ location.time_needed }}
    {% endfor %}
{% endfor %}

如果您真的不需要遍历这些字段。您可以使用slice选择实例

{{ employees.0 }}将根据您的查询集排序选择第一个employee实例

{{ employee.0.location.all.0 }}根据查询集排序选择第一个location实例

{{ employee.0.location.all.0.time_needed }}将为您提供对值的访问权。

或者更清楚的是:

{% with employees.0 as employee %}
     {% with location as employee.location.all.0 %}
         {{ location.time_needed }}
     {% endwith %}
{% endwith %}
票数 2
EN

Stack Overflow用户

发布于 2018-07-12 02:45:29

我想,你可以这样做:

employees = Employees.objects.all()
for employee in employees:
   for location in employee.location.all():
      print(location.time_needed)

如果你想访问一个特定的覆盖范围,那么你可以这样做:

Coverage.objects.filter(id__in=employee.location.all().values('id')).values('time_needed')
# This will return time_needed of all the Coverage whose id matched the location ids of employee
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51292150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档