I have a models like :
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)
In template, how can I get SellItems
using Invoice
object.
CodePudding user response:
you can use following snippet:
from models import Invoice
invoice = Invoice.objects.all().first()
if invoice and invoice.sell:
sell_items = invoice.sell.sell_item.all()
Just remember, that sell
could be none if there is no relation.
CodePudding user response:
to access reverse foreign key relationship, use _set
from the docs
your query:
invoice = Invoice.objects.first()
in your template:
{% 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 %}