Guilherme Soares
Guilherme Soares

Reputation: 736

How django works with foreign key?

I development system in Django and I really i love it. However I want improve my code but I have doubts how Django works with Foreign Keys.

Example:

class A(model.Models):
   b = model.IntegerField()

class C(model.Models):
   d = models.ForeignKey(A)


#getting...
value = C.objects.get(id=1)

print value.d.b

When i access property b from class A. Do django realize consult in DB? or realize consult in command C.objects.get(id=1)?

If django consult when i try to access property .Will he always consult in the database?

Upvotes: 0

Views: 101

Answers (2)

slim_chebbi
slim_chebbi

Reputation: 818

you can check Caching and QuerySets to understand who will be checked db or cache

Upvotes: 1

Nathaniel
Nathaniel

Reputation: 696

You could do something like this:

value = C.objects.select_related('d').get(pk=1)

This should prevent it from making another trip to the database.

See also https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related.

Upvotes: 1

Related Questions