我有一个模型,如:
class Invoice(models.Model):
created_date = models.DateTimeField(auto_now_add=True)
class Sell(models.Model):
invoice = models.OneToOneField(Invoice, on_delete=models.CASCADE)
class SellItems(models.Model):
sell = models.ForeignKey(
Sell, related_name='sell_item', on_delete=models.CASCADE)
item = models.CharField(max_length=200)
在模板中,如何使用Invoice
对象获得SellItems
可以使用以下代码段:
from models import Invoice
invoice = Invoice.objects.all().first()
if invoice and invoice.sell:
sell_items = invoice.sell.sell_item.all()
请记住,如果没有关系,sell
可能是none。
访问反向外键关系,使用文档
中的_set
查询:
invoice = Invoice.objects.first()
:
{% for sell in invoice.sell_set.all %}
<h1>{{ sell.pk }}</h1>
{% for sell_item in sell.sellitems_set.all %}
<h1>{{ sell_item.item }}</h1>
<br>
{% endfor %}
<br>
{% endfor %}