Good afternoon, the following problem arose: there is a model that stores images for the gallery.

class Gallery(models.Model): image = models.FileField(upload_to='gallery/') status = models.BooleanField() type = models.BooleanField() 

On the page this model is used to display as a gallery in the form of a tile, masonry. The tile is fixed and the problem is that you need to take 12 random pictures, it is easy.

 gallery = Gallery.objects.all().order_by('id','pk').order_by('?')[: 12]; 

But so that 5 of them have the type True, and the other 7 False. And if it is still possible to customize the order it would be generally perfect, well, let's assume that we have True - the picture is horizontal (d), and False is vertical (c). I would like to make a sample in which there will be, for example, such an order [c, d, d, d, c, c, c, d, d, c, c, c]

  • It is better to add a model code to the question and show what you have already tried to do than to lay out a wall of text - Ivan Semochkin
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

As far as I know, such filtering cannot be done in a simple way, not only at the Django ORM level, but also at the DBMS level. I would make such a list manually.

 qs = Gallery.objects.all().order_by('?') return [qs.filter(is_horizontal=True).first()] + [qs.filter...] + ... 

By the way, pk is just an alias for id , unless you have no fields in your model with primary_key=True . In addition, the subsequent .order_by() overwrites the previous one.

    If you solve the problem "in the forehead", you can take 2 slices from the objects of the queryset and display them in a template

     import itertools q_all = Galery.objects.all().order_by('?') q_true = q_all.filter(type=True)[:5] q_false = q_all.filter(type=False)[:7] galery = itertools.chain(q_true, q_false) 

    itetools.chain - itetools.chain 2 querisses into one, in the specified order
    To make a random order from the galery generator, you need to get its values ​​and use random.shuflle

     import random galery_lst = list(galery) random.shuffle(galery_lst)