Django tip: Merging QuerySets

/ #Django


Sometimes you need to merge two or more QuerySets, learn how to do it without losing functionality like filtering, counting, etc.

Introduction

Let's say that we have to models. A post and a category model like this:

class Post(models.Model):
    title = models.CharField(max_length=255)
    intro = models.TextField()
    body = models.TextField()

class Category(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    posts = models.ManyToManyField(Post)

Okay. So now imagine that you want to get all posts with "django" in the title + all the posts from a category called django.

posts_with_title = Post.objects.filter(title__icontains='django')
category = Category.objects.get(title='django')
posts_from_category = category.posts.all()

Right now, this will give us all the posts we want, but we still have two QuerySets. So let's merge them.

all_posts = posts_with_title | posts_from_category

So now we only have one QuerySet, but it has all the normal functionality like filtering, distinct, order_by, count and similar.

The problem on the other hand is that we might get many duplicates, so let's remove them as well.

all_posts = all_posts.distinct()

Now we have a variable called "all_posts" with the posts from the django category + other posts with django in the title.

Comments

Nurullo | Aug 25, 22 03:55

Thanks, now I know how to merge them help me a lot


Stein Ove Helset | Aug 25, 22 04:59

Great :-D

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.