2

Good day, I have a problem: I have a model with some fields.

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

I used this model for storing gallery image in masonry grid. This grid is fixed and I need to get 12 random image, this is easy to do.

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

But 5 of them should have True type, and 7 others - False. And I'll be insanely happy if it'll be able to custom an order in this queryset, for example, True means horizontal picture(h), False - vertical[v]. I want to get an order like this [v,h,h,h,v,v,v,h,h,v,v,v]

Black Fox
  • 23
  • 3
  • 1
    I am not sure if this is what you need; but what about `first getting 5 random True type, then getting 7 random False type and combine these two query results`? – alioguzhan May 15 '16 at 22:10

1 Answers1

1

You could do two queries, one for horizontal and one for vertical objects.

horizontal = Gallery.objects.filter(type=True).order_by('?')[:7]
vertical = Gallery.objects.filter(type=False).order_by('?')[:5]

Then construct the list from your two querysets

gallery = [verical[0]] + horizontal[0:3] + vertical[1:4] + horizontal[3:] + vertical[4:]

Note that the order_by docs warn that order_by('?') may be slow. If you hit performance problems, you might want to look for an alternative approach. See this question for example.

Community
  • 1
  • 1
Alasdair
  • 298,606
  • 55
  • 578
  • 516