I got two class models called Buy and Sell:
class Buy(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
image = models.FileField()
date = models.DateField()
buy_price = models.DecimalField(max_digits=6, decimal_places=2)
sell_price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return str(self.id)
class Sell(models.Model):
item = models.OneToOneField(Buy, on_delete=models.CASCADE)
date = models.DateField()
discount = models.DecimalField(max_digits=6, decimal_places=2)
total_paid = models.DecimalField(max_digits=6, decimal_places=2)
buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE)
def __str__(self):
return str(self.item)
In a template, I'd like to display all the records from the Sell table and also the image class-attribute from Buy table.
Below, my view.py:
def sell(request):
buys = []
sells = Sell.objects.order_by('-id')
for sell in sells:
buys.append(Buy.objects.filter(id=str(sell.item)))
context = {'sells': sells, 'buys': buys}
return render(request, 'sell.html', context)
Template:
{% for sell in sells %}
<tr>
<td>{{ sell.item }}</td>
<td>{{ sell.date|date:'d-m-Y' }}</td>
<td>{{ buys[0].image}}</td>
<td>R$ {{ sell.discount }}</td>
<td>R$ {{ sell.total_paid }}</td>
<td>{{ sell.buyer }}</td>
</tr>
{% endfor %}
I'm wondering if there is a simple way to do that. I need some help in my view.py!