Reputation: 8722
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
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