What ready-made solutions exist for storing images to the product to the product catalog.

It is required either a ready-made minimal implementation example or an application with minimal functionality, monsters like oscar are not needed here.

Parsed options. One-to-one connection, json field, GenericRelation.

Disadvantages:

json - you have to do a lot

foreign key - a large number of requests

GenericRelation - requests, difficulty in understanding the code.

I would like to find the optimal solution, preferably ready to connect to the project.


Note

The proposed @FeroxTL solution through prefetch_related is both the most popular and the most optimal in terms of performance. In addition, there is always the possibility of speeding up through redundancy by copying data for output into an additional field in the product table.

Addition of the answer

  1. supplements this answer, how to add to the admin area

  2. snippet sorting, requires minor refinement for images

  3. ready application from which it is possible to use code sections, for example saving of the image

  • Use select_related() and there will be no more requests when using a ForeignKey . - Sergey Gornostaev

1 answer 1

Classically, this problem is completely solved by django tools without any additions. You’ll get one model for product presentation and one model for images, like this:

 class Product(models.Model): name = models.CharField('Название', max_length=200) class ProductImage(models.Model): product = models.ForeignKey(Product, verbose_name='Товар', related_name='images') image = models.ImageField('Изображение', upload_to='images') 

To select all products with their images, use prefetch_related :

 qs = Product.objects.all().prefetch_related('images') 

Then in the cycle you can sort the goods as follows:

 for product in qs: print(qs.name) for image in product.images.all(): # дополнительных запросов не будет print('->', image.url) 

Technically, this will be implemented as 2 requests for any number of results - the first request loads the goods, the second - pictures of the loaded goods. For a programmer, this happens transparently; no gestures are required.

  • from which model to which connection is there, in the example there is no data about it? - Igor
  • @Igor I apologize, I changed it in my editor, and in response I forgot to copy the changes. Corrected the answer. Of course, the link from ProductImage to Product should be - FeroxTL
  • The answer is correct. Added information that complements this answer to the question, because in the comments will not be visible, edit until there is a full working code is not right - Igor