Django与select_related的反向关系 [英] Django reverse relation with select_related

查看:209
本文介绍了Django与select_related的反向关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个模型,我想检索他们之间的联系。



ModelA


$ b $
product = models.ForeignKey(ModelB)
group = models.ForeignKey(Group)

ModelB

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

ModelC

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

ModelD

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

现在,我想让我所有的 ModelA 对象与 ModelB ModelC ModelD
在sql中这是一件很容易的事情。只需在表之间连接。
与Django ORM我陷入困境,因为我只能做远程关系。



我在做这个

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

但我不能加入ModelC
我已经读过这篇文章,但我不想循环我的大名单,做一个简单的事情!我只想打数据库一次。



我正在使用最后一个版本的Django,我希望已经有一个解决方案,我没有意识到的



谢谢。

解决方案

请参阅 prefetch_related 。它只是在目前的开发,但将会与Django 1.4。如果可以等待或者可以在树干上运行。您可以使用它。



同时,您可以尝试 Django的批量选择。它基本上服务于相同的目的。


I have 4 models and i want to retrieve a join between them

ModelA

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

ModelB

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

ModelC

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 joined with ModelB, ModelC and ModelD In sql this is pretty easy thing to do. Just make joins between tables. With Django ORM i'm stuck because i only can do forward relation.

I'm doing this

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

But i can't join ModelC I already have read this article, but i don't want to loop over my big list, to do a simple thing! And i want to hit database only once.

I'm using the last version of Django and i hope there is already a solution to this, that i'm not aware of.

Thank you.

解决方案

See docs on prefetch_related. It's dev only at the moment, but will hit with Django 1.4. If you can wait or you can run on trunk. You'll be able to use that.

In the meantime, you can try django-batch-select. It essentially serves the same purpose.

这篇关于Django与select_related的反向关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆