We have 2 models.

class News(models.Model): title = models.CharField(max_length=250) еще дата публ, кол-во просмотров и т.д. class Images(models.Model): image = models.ImageField(upload_to="news/images/%m.%Y") news = models.ForeignKey(News, related_name='images2news') 

News can have> = 0 images. How to choose all the news along with the pictures if the news of course they are?

There is already an incorrect implementation that generates duplicates.

 News.objects.filter(site=1).values('pk', 'title', 'text', 'changed', "images__image").order_by("-changed").distinct() 

    1 answer 1

    To avoid the n + 1 query problem, in the reverse ForeignKey (your case), use django-batch-select

    set it to your surroundings:

     pip install django-batch-select 

    better add to the file requariments.txt

    after which you need to change the objects manager for the models with which you intend to use it. In your case:

     from batch_select.models import BatchManager class News(models.Model): title = models.CharField(max_length=250) *** objects = BatchManager() 

    And you can safely select all the news with their pictures in one request:

     news = News.objects.filter(site=1).batch_select('images') for n in news: print n.title print n.images_all 

    Note: now the list of objects of the images class is available through the <related_name>_all , you can change this behavior, for example: batch_select (images = 'images'). It is possible to perform complex compound queries and aggregations in the same way, for more details see the batch_select documentation

    Yes, and, in your model inaccurate related_name:

     news = models.ForeignKey(News, related_name='images2news') 

    in my example, I used related_name = 'images'