Reputation: 1044
How do I know if Django is running multiple queries when fetching a model that contains relations?
Here is an example:
class ModelOne(models.Model):
'''...the stuff...'''
class ModelTwo(models.Model):
something = models.ForeignKeyField(ModelOne)
'''...all the things...'''
class ModelThree(models.Model):
something_elses = model.ManyToManyField(ModelTwo)
class ModelFour(models.Model):
now_this_is_just_silly = models.ManyToManyField(ModelThree)
So lets say I fetch ModelFour like so:
m = ModelFour.objects.all()[0]
It would be wonderful to think that, by default, all submodels all the way down to ModelOne
are a part of it's datastructure. Is that the case?
If I start to navigate down the datastructure of ModelFour to access an attribute (the stuff) in ModelOne, am I performing multiple queries?
For the record, this is a postgres database setup, per django suggestion.
Upvotes: 0
Views: 64
Reputation: 1307
To count nr of queries try using connection from django.db (make sure DEBUG=True
in settings.py):
from django.db import connection
m = ModelFour.objects.all()[0]
print len(connection.queries)
...and if you just want to see the queries in a list, remove len
Upvotes: 1
Reputation: 18242
You can look at postgres' query count and check it again after your query has finished
Use this query to read total number of transactions executed in all databases:
SELECT sum(xact_commit+xact_rollback) FROM pg_stat_database;
If you want the same counter for just one database, use:
SELECT xact_commit+xact_rollback FROM pg_stat_database WHERE datname = 'mydb';
credit to: https://dba.stackexchange.com/questions/35940/how-many-queries-per-second-is-my-postgres-executing
You can list the current running queries with:
SELECT datname,procpid,current_query FROM pg_stat_activity
from: http://chrismiles.info/systemsadmin/databases/articles/viewing-current-postgresql-queries/
Upvotes: 1