如何在Django中获取相关集(多对多字段)

时间:2018-07-11 18:32:56

标签: django django-models django-templates django-views

我有一个员工模型

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.objects.all())从模板中获取时间-

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

ps:这只是更大的模型类的片段

2 个答案:

答案 0 :(得分:2)

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.0.location.all.0 }}根据查询集的顺序选择第一个位置实例

{{ employee.0.location.all.0.time_needed }}将使您可以访问该值。

或更清晰:

{% with employees.0 as employee %}
     {% with location as employee.location.all.0 %}
         {{ location.time_needed }}
     {% endwith %}
{% endwith %}

答案 1 :(得分:1)

我想,您可以执行以下操作:

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

如果您想访问特定的Coverage,则可以执行以下操作:

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