0

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?

Wtower
  • 18,848
  • 11
  • 103
  • 80
saarthak gupta
  • 173
  • 1
  • 11
  • Why don't you share the query with us. – Wtower Jun 10 '15 at 11:06
  • 3
    Possible duplicate of [this](http://stackoverflow.com/questions/971667/django-orm-how-to-view-or-log-the-executed-query) – Vaulstein Jun 10 '15 at 11:08
  • 2
    Do you know about the django debug toolbar: https://django-debug-toolbar.readthedocs.org/en/1.3/ It displays all the queries that execute for a request – joel goldstick Jun 10 '15 at 11:27
  • @Wtower cant share the query as it is related to work, but I now have a fair idea of how to debug Django queries. Thank you Vaulstein for the redirect, but my question is in the reverse direction - I have a query and I need to know which models were involved when that query was triggered. Thank you, Joel Goldstick. Will check it out. Thanks all – saarthak gupta Jun 12 '15 at 06:14

1 Answers1

0

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.

Vaibhav Kumar
  • 518
  • 3
  • 12