Home > front end >  Django: template to list data from 2 models related each other
Django: template to list data from 2 models related each other

Time:06-06

I have 2 models. One of them is primary key of the other as in example below.

class Product(models.Model):
    name = models.CharField(max_length=32, unique=True)
    power = models.IntegerField(default=0)


class Price(models.Model):
    product = models.OneToOneField(Product, on_delete=models.PROTECT, primary_key=True)
    price = models.IntegerField(default=0)

I'd like to build a template that displays the data from the 2 models. For example:

List of Products

product: P_A    power: 1000W   price: $
product: P_B    power: 1500W   price: $
product: P_C    power: 2000W   price: $

I have made several attempts without being successful in displaying the prices. One of them were the following template and view:

    <h2>List of Products</h2>
<ul>
    {% for product in list_of_products %}
        <li>product: {{ product.name }} &emsp; &emsp;power: {{ product.power }}W &emsp; price: {{prices.product.price }} $</li>
    {% endfor %}
</ul>

def index(request):
    products = Product.objects.all()
    prices = Price.objects.all()
    return render(request, "index.html", {'list_of_products': products, 'prices': prices})

CodePudding user response:

You should not pass a queryset of Prices to the template, you can work with:

def index(request):
    products = Product.objects.select_related('price')
    return render(request, "index.html", {'list_of_products': products})

Then in the template, you render this with:

{% for product in list_of_products %}
    <li>product: {{ product.name }} &emsp; &emsp;power: {{ product.power }}W &emsp; price: {{ product.price.price }} $</li>
{% endfor %}

It is however not clear to me why you do not store the price in the Product model here, and work with a separate model.

  • Related