[Fixed]-Is that Django model query correct?

1👍

Theres nothing wrong with long queries providing your use case requires it, however your query shown contains a lot of unnecessary internal database queries to figure out what you wish to search with __in. You should be able to rewrite it to the following.

goodbills = Billinfo.objects.filter(status=20,
                                    lead__link__partner=self.id,
                                    lead__link__landing=eachlanding).count()

This removes the need to retrieve the link objects and the lead objects (and in my opinion makes it easier to understand).

👤Sayse

0👍

It is usually a good idea to keep your queries in order to keep them easy to read and maintain as well as preventing the database engine from working too hard. However, sometimes you have to run queries that are complex and there is not much you can do.

Without knowing your ERD (Entity Relationship Diagram) it is hard to comment how to better structure that query. But at the very least, I would do something like:

link_ids = Link.objects.filter(partner=self.id, landing=eachlanding)
lead_id = Lead.objects.filter(link_id__in=link_ids).values_list('id')).values_list('id')

goodbills = Billinfo.objects.filter(status=20, lead_id__in=lead_ids)

This would make sure that the first two queries do not run every time you call the goodbills query.

Leave a comment