django-models

Will Django query database for related model if I only access the pk?


Simple question here.

I have two models "Apples" and "Bananas". Model Apple has an FK relationship with Banana.

If I run myApple = Apple.objects.get(pk = pk) then django runs a SQL query to fetch the data. If I want to access Banana from this "myApple" variable, then django will run another query to fetch the related object, but what if I only want to access the PK for an apple serialiser?

Will Django run another SQL query if all I'm doing is "return myApple.banana.pk"?

I could add a .select_related of course, but seems unneccesary if the PK is returned as part of the foreign key value when returning the original Apple query.


Solution

  • Will Django run another SQL query if all I'm doing is return myApple.banana.pk?

    Yes, but the good news is, you can get the primary key without fetching, by using:

    myApple.banana_id

    If you define a ForeignKey named foo, you get a foo_id field as well that stores the column the ForeignKey refers to.