我有以下模型类称为A和B,它们由外键关联。所以B有一个关于外键的链接回到a。我现在想通过A循环,提取出可能大量的B类。现在是一个转折点,在模板中显示这些内容最聪明的方法是什么?你知道吗
class A(models.Model):
field1 = models.CharField(max_length=30)
class B(models.Model):
aAID = models.ForeignKey(A)
field1 = models.CharField(max_length=30)
现在,获取A非常容易,因为我得到了查询集,即
alla = A.objects.all().order_by("-date")
然后我可以通过一个呈现将其发送到一个模板并通过alla进行循环,但是我如何在该模板中也能够通过找到的B类进行循环呢。你知道吗
您可以使用自动创建的管理器
a.b_set
执行以下操作:或在模板中:
还可以看看the official documentation。你知道吗
可以像模板中的其他属性一样循环相关成员,因此可以执行以下操作:
这只是一个例子。在模板中做你想做的事
A
类具有b_set
属性,该属性返回相关的B
对象。你知道吗可以在模板中使用此属性:
引用一位伟人的话:
相关问题 更多 >
编程相关推荐