How can I reverse a SQL Query to reach its Django source?

352 Views Asked by At

Is it possible to reverse a complex sql query (consisting of joins and group by) to reach its Django source?

By source, I mean the model that might have triggered the query?

For example, consider the models:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

A query that uses group by and left outer join on these models is fired. Can I trace it back?

1

There are 1 best solutions below

0
On

May be this is the answer you are looking for.

Actually what i got from your comment 'I have a query and I need to know which models were involved when that query was triggered', you want to trace the models/tables which is getting involved in your query.

So for that you can use .query over your object.E.g;

exm = Example.objects.all()

print exm.query # This will give you the query which will be triggered in the back-end.

You can debug from your code or you can use django-debug-toolbar.