我的两个模型:
class BusinessType(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
class Business(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
bus_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE, name="type")
class Appointment(models.Model):
from datetime import datetime
business = models.ForeignKey(Business, on_delete=models.CASCADE, name="appointments")
done = False
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
现在,我将此上下文添加到我的视图中:
'business':Business.objects.order_by('name'),
我的模板:
{{business|length}}<hr />
{%for business_entry in business%}
{{business_entry.appointments.all|length}}
{%endfor%}
现在业务长度输出为“ 2”,是的,我有两个业务对象。
但是对于约会,我得到的值为“ 0”,这是不正确的。
我在做什么错了?
答案 0 :(得分:1)
应为related_name="appointments"
,而不是name="appointments"
。
因此,更改:
business = models.ForeignKey(Business, on_delete=models.CASCADE, name="appointments")
收件人:
business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name="appointments")
您可能需要阅读:ForeignKey.related_name