Skip to content

Instantly share code, notes, and snippets.

@barseghyanartur
Last active August 22, 2019 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barseghyanartur/5a1b048f43fc64a46b96124f8c144737 to your computer and use it in GitHub Desktop.
Save barseghyanartur/5a1b048f43fc64a46b96124f8c144737 to your computer and use it in GitHub Desktop.
Django: Select 3 most recent Post objects from 3 different users in a single database query

Task

Given:

  • There are a lot of Post objects.
  • There are 3 users.

What we want:

  • Select 3 most recent Post objects from 3 different users.

Models

class Post(models.Model):

    title = models.TextField()
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    date = models.DateTimeField()

Implementation

qs_1 = Post.objects.filter(user_id=1).order_by('-date')

qs_1.query.set_limits(0, 1)

qs_2 = Post.objects.filter(user_id=2).order_by('-date')

qs_2.query.set_limits(0, 1)

qs_3 = Post.objects.filter(user_id=3).order_by('-date')

qs_3.query.set_limits(0, 1)

qs = Post.objects.none()

qsa = qs.union(qs_1, qs_2, qs_3)

print(qsa)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment