N
N
NyxDeveloper2021-03-03 18:22:04
Django
NyxDeveloper, 2021-03-03 18:22:04

How to get all objects linked via ForignKey from QuerySet of linked object model?

There was a problem with the speed of executing queries to database tables due to the strong nesting of objects.
Models:

class Model1(models.Model):
    field = models.CharField(max_lenght=100)

class Model2(models.Model):
    field = models.ForignKey(Model1, 'model_1', related_name='model_1', on_delete=models.CASCADE)

class Model3(models.Model):
    field = models.ForignKey(Model2, 'model_2', related_name='model_2', on_delete=models.CASCADE)

How can I get a QuerySet of Model3 objects linked through Model2 objects to Model1 objects. However, without using something like this:
Model3.objects.filter(model_2__model_1_id__in=Model1.objects.filter(.....).values('id'))

The given request fulfills terribly long, even on the minimum data set. In the official documentation, I found the select_related and prefetch_related methods, but I didn’t quite understand how they work and I’m not sure if I even need them. Please tell me the correct solution to this problem, I'm sure it's easy, just not obvious. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-03-03
@bacon

it should not be long, maybe something else slows down here, put django-debug-toolbar and see what request and its plan

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question