2

I want to combine these 2 queries in 1 to get the Music object with name xyz and also get top 3 objects from genre 10, ordered by artist:

1. Music.objects.filter(name='xyz', genre=10)

2. Music.objects.filter(genre=10).order_by('artist')[:3]

I can use Q objects like this but I don't know how to order & filter the 3rd Q object below:

Music.objects.filter( (Q(name='xyz') & Q(genre=10)) | Q(genre=10) )
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
click
  • 2,093
  • 2
  • 15
  • 21

2 Answers2

0

Maybe try like this?

Music.objects.filter( (Q(name='xyz') & Q(genre=10)) | Q(genre=10) ).order_by('artist')[:3]
Dmitry Yudin
  • 1,033
  • 1
  • 10
  • 31
  • This is incorrect. I want object with name `xyz` + top 3. This will simply get top 3. It won't ensure that the results have the object with name `xyz` – click Aug 18 '14 at 19:32
  • This is logically equivalent to `Music.objects.filter( Q(name='xyz') | Q(genre=10) ).order_by('artist')[:3]` – Lorenzo Peña Dec 14 '15 at 21:20
  • Also @click, there is now way to do it. You want four results that come from two different queries, why would you want to use a single query? – Lorenzo Peña Dec 14 '15 at 21:21
0

No way to do it, use two queries but change second to avoid duplicates:

exact = Music.objects.filter(name='xyz', genre=10)
additional = Music.objects.filter(genre=10).exclude(name='xyz').order_by('artist')[:3]
do_something_with = list(exact) + list(additional)
Lorenzo Peña
  • 2,225
  • 19
  • 35