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)