How does this code? GET method and Q objects

116 views Asked by At

How does this code? step-by-step

keyword = request.GET['keyword']
for l in keyword.split():
    q = q | (
        Q(title__icontains=smart_str(l)) |
        Q(content__icontains=smart_str(l)) 
        )
    result = News.objects.filter(q)

What is happening in each line?

1

There are 1 answers

0
Mikael On BEST ANSWER

You are receiving a list of keywords from the GET call which you then split up into a list of keywords.

You loop through the keywords and for each of them you build an OR query which is stored in q. You are querying the database for News objects where the keywords are found in the title OR the content.

In the last row you are filtering out the News items matching your query.

You can find more information about the Q parameter here: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

The | char means OR.