smoquet
smoquet

Reputation: 371

When does django query the database when acceessing a related model instance through the foreignkey relationship?

This is an example model definition:

class Glass(model):
    type = models.CharField(max_length=255)

class Window(model):
    glass = models.ForeignKey(Glass)

class House(model)
    window = models.ForeignKey(Window)

Dotwalking the foreign keys of the mentioned models and getting the related objects.

house = House.objects.get(pk=1)
window = house.window
glass= house.window.glass

I understand that to get house a query is run. Then when I get house.window I presume a second query is run to get an instance of the window. And when accessing glass does Django already have the window loaded in the instance of House? Or does it query window again?

I can't seem to find the exact answer to this question online or in the Django docs.

Answer would be great to further my understanding of Django ORM querying.

Cheers!

Upvotes: 0

Views: 69

Answers (1)

tstoev
tstoev

Reputation: 1435

each time you trigger the orm a query is made, the first line creates an instance of house and to do that it loads it with data, the same is true for the second line but for an instance of window and for the third line for an instance of glass. You can merge those queries by adding prefetch_related as a paramter in the first query. If you do not want the second and/or third query you can access the id field directly by using house.window_id(bypass the orm by accessing the attribute directly). If you do use house.window.id however you will trigger the orm to create a window instance.

Upvotes: 1

Related Questions