[Fixed]-Django: how to get Product and ImageProduct

1👍

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.

👤Wtower

Leave a comment