python – Custom filter for querysets


Good afternoon, the following problem has arisen: 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, this is not difficult.

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

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


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 by hand.

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 fields with primary_key=True in your model. In addition, the subsequent .order_by() overwrites the previous one.

Scroll to Top