0

I have 2 models for global tags and user tags. Both Global_Tag and User_Tag have common field encapsulated in an abstract class. When a user is logged in I show user both user tags and global tags in a list sorted by name. I have defined a queryset of global_tag and user_tag and later doing union on them and order by name.

Now my question is if django is actually firing 3 query to database or just 1 query. In pycharm debugger I see it printing data as soon as global_tag queryset is defined and later for user_tag queryset as well. Later for union queryset as well. So my question is django firing 3 queries to db or 2 and doing union and order by in memory OR just firing 1 query to db. I need output of only union query. What the best way to have django only fire last query and not 2 queryset used for preparation of final query.

CJT
  • 83
  • 1
  • 10
  • 1
    The reason that makes queries to the database is because the debugger calls `str(..)` on these querysets for debugging purposes, if you do not "consume" the two queryset's, then no queries will be done, and the union will thus produce one database hit. – Willem Van Onsem Sep 24 '21 at 14:01
  • Thanks @WillemVanOnsem. This is good to know otherwise I was wondering If I am overloading databases using django. A related question is if there is a way to see queries that are fired by django models at run-time or if there is a way to create a separate log files for them. – CJT Sep 24 '21 at 14:15
  • Yes, see here how you can log all the queries of the database backend: https://stackoverflow.com/a/20161527/67579 (for example to a file). Then you can run a certain view (not with the debugger, since as said, the debugger will trigger extra queries), and then look in the file to see what queries have been triggered. – Willem Van Onsem Sep 24 '21 at 14:17
  • Thanks! I ran the app and noticed django firing 2 union query to db. 1 with limit 21 (ORDER BY (6) ASC LIMIT 21; args=(1, 114, False, 114)) and another without any limits . I guess this has to do with pagination but I don't have any pagination implemented. Wondering if there is any django guidelines to remove this additional call to db. – CJT Sep 24 '21 at 14:37
  • no, the limit 21 is builtin, it is Django's way to limit the amount of data that flows from the database to the django app. It will make second call if there are more rows. – Willem Van Onsem Sep 24 '21 at 14:39

0 Answers0