Search code examples
djangodjango-modelsdjango-querysetdjango-ormdjango-select-related

how to optimize the query here with select_related?


i have

class A(models.Model):
    field_a = models.OneToOneField(B, on_delete=models.CASCADE)

class B(models.Model):
    field_b = models.charField()

how to write the most optimum query here using select_related or something else? In my use case i need to use both, field_a of model A and field_b of model B somewhere in my code. So can i fetch both the objects in one db hit?

queryset_b = B.objects.get(field_b="some name")
queryset_a = A.objects.get(b=queryset_b).field_a
field_a_of_model = queryset_a
field_b_of_model = queryset_b.field_b
# then some manipulation with both fields

it hits the db twice. Can i do this thing in one db hit using select_related so that it fetches both object at once?


Solution

  • You could use lookup that span relationship

    a = A.objects.get(b__field_b="some name")
    

    This would result in single query to database


    If you want single query to access fields from b too use select_related()

    a = A.objects.select_related().get(b__field_b="some name")
    a.field_a.field_b