如何在Django中获得关联集(多到多个字段)?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (442)

我有一个员工模型

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}}但它不起作用。

提问于
用户回答回答于

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 %}
用户回答回答于

我想,你可以这样做:

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

扫码关注云+社区

领取腾讯云代金券