Programmingjoe
Programmingjoe

Reputation: 2259

Django - Turning code into django query?

So I have this django query that I am making on one of my models and I have some extra python code that is used to do additional work in between each query. I am looking for some assistance in turning this chunk of code into a single django query as I know you should be making the database do most of the work.

The query code is below.

keywords = []
if query:
   results = []
   keywords = query.split()
   for x in keywords:
      res = Textbook.objects.filter(Q(class_name__icontains=x) |
                                    Q(textbook_name__icontains=x) |
                                    Q(author__icontains=x) |
                                    Q(isbn__icontains=x))
      if len(results) == 0:
         results = res
      else:
         results = set(results) & set(res)

numresults = len(results)

So query is the information I take from the user. I split up this information into keywords and make a query for each keyword. They are searching for textbooks so if any word they enter matches the isbn, title, class name, or author of a book it is added to the results. However, if they used multiple words I only add it to the results if both words return the book as a query. That's what results = set(results) & set(res) does. If the current results and the new query return the same book keep it in the results.

I know this is bad so I am looking for a way to improve it.

Upvotes: 0

Views: 158

Answers (1)

Ritave
Ritave

Reputation: 1373

You can do additional filters in the loop instead of set-intersection:

keywords = []
if query:
    results = []
    keywords = query.split()
    query = Textbook.objects.all()
    for x in keywords:
        query = query.filter(Q(class_name__icontains = x) | Q(textbook_name__icontains = x) | Q(author__icontains = x) | Q(isbn__icontains = x))

numresults = len(query)

Since Django's QuerySets are lazy, SQL call should be deffered until numresults = len(query) line

Upvotes: 8

Related Questions