Django custom foreign key representation

If i have two models

class Parent(models.Model):
    attribute_1 = ....
    attribute_2 = ....

class Child(models.Model):
    parent = models.ForeignKey(Parent)

Django by default will do lazy fetching to parent as it will hit the database when i try to access attribute_1 or attribute_2, so how can I make it fetch them by default for this specific use case

Use select_related when fetching your child object(s) to also fetch the data for the foreign key in a single query

child = Child.objects.select_related('parent').get(id=1)
print(child.parent.attribute_1) # No additional query
print(child.parent.attribute_2) # No additional query
Back to Top