0

I'm new to django so please bear with me.

I have the below relationships. If I have the primary key of model A, how can I get all the data from A, B and C in the most efficient query?

Note: A -> C is a 1 to many relationship while B -> C is a many to one relationship (ie each C only has 1 B, but multiple Cs may have the same B).

I was thinking of some form of prefetch_related but as I understand it, that implies I am making 3 db calls?

Also, is there somewhere I can see the SQL query that Django runs? I am using mysql as a db.

Class A(models.Model):
    pass

Class B(models.Model):
    pass

Class C(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)
Terence Chow
  • 10,755
  • 24
  • 78
  • 141

1 Answers1

0

You can use select_related instead:

C.objects.filter(<your filter if any>).select_related('a', 'b')

This will retrieve all the data from the DB for the related fields a and b, in a single query. You can see the difference with prefetch_related here.

In regard your second question

is there somewhere I can see the SQL query that Django runs?

Yes, you can see them using django-debug-toolbar, in the panel SQL.

trinchet
  • 6,753
  • 4
  • 37
  • 60
  • Are there unnecessary joins considering every C is connected to the same A? (Note my question said I have the A.id) – Terence Chow Jul 05 '18 at 17:13
  • There is no unnecessary joins, this is the more efficient way to do what you need, read the documentation for more details. Also, you can see the raw query that is executed using `django-debug-toolbar`, give it a try and you will see the benefits. – trinchet Jul 05 '18 at 17:25