javad75
javad75

Reputation: 1435

django: how to get Product and ImageProduct

I have two models/tables:

  1. Product

  2. ImageProduct

ImageProduct has ForeignKey to Product

class ImageProduct(models.Model):
    url = models.ImageField(max_length=350,
                            null=True,
                            blank=True,
                           )

    product = models.ForeignKey('Product',
                                null=True,
                                blank=True,
                                on_delete=models.CASCADE,
                               )

I want to get last product with image product in indexpage, so I use:

last_product = Product.objects.all()

last_product returns all products

How to get ImageProduct for each product and use in template:

    {% if last_product %}{% for product in last_product %}
      <article class="article cfix">
        <figure>
          <img src="{{ ??? }}" />
        </figure>
        <header>
          <h2 class="header-inline">{{ product.name }}</h2><span class="date-time header-inline">[ 3 روز پیش ]</span>
        </header>

      </article>
    {% endfor %}{% endif %}

Upvotes: 0

Views: 55

Answers (1)

Wtower
Wtower

Reputation: 19902

As it is currently coded, your ImageProduct has an many-to-one relationship to Product. This essentially means that a Product can have many ImageProducts.

Please also note that the variable name last_product is misleading, it should be eg. products to avoid confusion, as it is a queryset and not a single model.

So you could access the last product with something like last_product = products.last().

You can access the related set of ImageProducts from the parent with this:

last_product.imageproduct_set

If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. This Manager returns QuerySets, which can be filtered and manipulated as described in the “Retrieving objects” section above.

Reference: Following relationships “backward”.

See also the documentation for related_name if you wish to change the imageproduct_set.

Upvotes: 1

Related Questions