python Django:select_related 与 ManyToManyField

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1387044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:06:45  来源:igfitidea点击:

Django : select_related with ManyToManyField

pythondjangodjango-modelsdjango-select-related

提问by Paul Tarjan

I have :

我有 :

class Award(models.Model) :
    name = models.CharField(max_length=100, db_index=True)

class Alias(models.Model) :
    awards = models.ManyToManyField('Award', through='Achiever')

class Achiever(models.Model):
    award = models.ForeignKey(Award)
    alias = models.ForeignKey(Alias)
    count = models.IntegerField(default=1)

How can I have an Aliaswhich has all its achiever_setand awardsprepopulated?

怎样才可以有一个Alias具有其所有achiever_set,并awards预填?

>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("achiever_set__award").get().achiever_set.all()[0].award.name
u'Perma-Peddle'
>>> len(db.connection.queries)
3
>>> db.reset_queries()
>>> Alias.objects.filter(id="450867").select_related("awards").get().awards.all()[0].name
u'Dwarfageddon (10 player)'
>>> len(db.connection.queries)
2

I'm going to need a lot of access to the award that an alias has already gotten (both the intermediate table and the awards themselves). How can I batch all of these?

我将需要大量访问别名已经获得的奖励(中间表和奖励本身)。我怎样才能批量处理所有这些?

回答by Vebjorn Ljosa

Django versions 1.4 and above have prefetch_relatedfor this purpose.

Django 1.4 及以上版本已prefetch_related用于此目的。

The prefetch_relatedmethod is similar to select_related, but does not do a database join. Instead, it executes additional database queries and does the joining in Python.

prefetch_related方法类似于select_related,但不执行数据库连接。相反,它执行额外的数据库查询并在 Python 中进行连接。

回答by Shane

If you're not on Django 1.4, there's also the django-batch-selectlibrary, which works basically the same way as prefetch_related.

如果您使用的不是 Django 1.4,还有django-batch-select库,它的工作方式与 prefetch_related 基本相同。