0

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!

frnhr
  • 12,354
  • 9
  • 63
  • 90
Felipe Dourado
  • 441
  • 2
  • 12
  • Not related, but this `for` loop will become bad quickly. Perhaps try something like this: `buys = sells.select_related("item").values_list("item", flat=True)` – frnhr May 07 '20 at 18:50

1 Answers1

2

You can access the Buy entity related to the Sell inside the template

{{sell.item.image}}

If the image field is as the name suggests a image you might want to change the field to a ImageField.

Then the code to display the image would be:

<img src="{{ sell.item.image.url }}">

(found here)

bb4L
  • 899
  • 5
  • 16
  • 1
    If `{{ sell.item.image ]}` is in a for loop, use `select_related` on the queryset in the view. Ref [select_related docs](https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.select_related) – frnhr May 07 '20 at 18:53