Django Feedback with select_related

I have 4 models and I want to get a connection between them

Modela

class ModelA(models.Model): product = models.ForeignKey(ModelB) group = models.ForeignKey(Group) 

ModelB

 class ModelB(models.Model): title = models.CharField() 

model

 class ModelC(models.Model): product = models.ForeignKey(ModelB) group = models.ForeignKey(ModelD) 

Modeld

 class ModelD(models.Model): name = models.CharField() 

Now I want all my ModelA objects to be combined with ModelB , ModelC and ModelD. In sql, it's pretty easy. Just create joins between tables. With Django ORM, I'm stuck because I can only do a direct relationship.

I'm doing it

 ModelA.objects.all().select_related(product) 

But I canโ€™t join ModelC I already read this article , but I donโ€™t want to go through my big list, do a simple thing! And I want to get into the database only once.

I am using the latest version of Django, and I hope that there is already a solution for this that I do not know about.

Thanks.

+7
source share
2 answers

See the prefetch_related docs. This dev is only for now, but will fall into Django 1.4. If you can wait or you can work on the trunk. You can use it.

At the same time, you can try django-batch-select . This essentially serves the same purpose.

+8
source

Edit: After re-checking the problem, the solution is not so simple.

docs say:

select_related limited to a one-to-one relationship - a foreign key and one to one.

Django 1.4 requests will have a prefetch_related method, which you must read. It looks like you wonโ€™t be able to do this in one request, but you can do it in 2 or 3. You definitely need to take a look and upgrade to the dev version if you really need to.

If you cannot use the dev version and cannot wait for 1.4, django also supports custom SQL queries .

+3
source

All Articles