在Django temp中显示多个相关类

2024-09-30 12:12:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下模型类称为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类进行循环呢。你知道吗


Tags: 方法模型模板内容model链接modelslength
3条回答

您可以使用自动创建的管理器a.b_set执行以下操作:

>>> for a in A.objects.all():
>>>     for b in a.b_set.all():
>>>         print b.field1

或在模板中:

{% for a in alla %}
    {% for b in a.b_set.all %}
        {{ b.field1 }}
    {% endfor %}
{% endfor %}

还可以看看the official documentation。你知道吗

可以像模板中的其他属性一样循环相关成员,因此可以执行以下操作:

<table>
{% for a in alla %}  
    {% for b in alla.b_set.all %}
         <tr><td>{{a}}</td><td>{{b}}</td></tr>
    {% endfor %}
{% endfor %}
</table>

这只是一个例子。在模板中做你想做的事

A类具有b_set属性,该属性返回相关的B对象。你知道吗

可以在模板中使用此属性:

{% for a in alla %}
  {{ a }}
  {% for b in a.b_set.all %}
    {{ b }}
  {% endfor %}
{% endfor %}

引用一位伟人的话:

When you define a relationship in a model (i.e., a ForeignKey, OneToOneField, or ManyToManyField), instances of that model will have a convenient API to access the related object(s).

[...]

Django also creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Blog object b has access to a list of all related Entry objects via the entry_set attribute: b.entry_set.all().

相关问题 更多 >

    热门问题