darkhorse
darkhorse

Reputation: 8722

Applying filter to queryset only when query is provided in Django

Let's say I have a model called Article with the field title. I have a method that returns a queryset for this model, and the method takes an optional argument called query which if provided, is used to filter out the queryset. So something like this:

def get_articles(query=None):
    if query:
        return Article.objects.filter(title__icontains=query)
    else:
        return Article.objects.all()

This works fine, but notice how this method has two return statements, as in, I'm writing out two separate queries. Is there a way to do this in one go? In other words, the ideal scenario would be writing just one query instead of two. Thanks for any help.

Upvotes: 1

Views: 81

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can reduce the number of return statements to one with:

def get_articles(query=None):
    qs = Article.objects.all()
    if query:
        qs = qs.filter(title__icontains=query)
    return qs

Upvotes: 1

Related Questions