我有一个员工模型
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 :这只是一个更大的模型类的一小段
发布于 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 %}
发布于 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
https://stackoverflow.com/questions/51292150
复制相似问题