如何结合Django“ prefetch_related”和“值”方法? [英] How to combine django "prefetch_related" and "values" methods?

查看:112
本文介绍了如何结合Django“ prefetch_related”和“值”方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何结合使用 prefetch_related values 方法?

How can prefetch_related and values method be applied in combination?

以前,我有以下代码。为优化性能,此查询中的限制字段是必需的。

Previously, I had the following code. Limiting fields in this query is required for performance optimization.

Organizations.objects.values('id','name').order_by('name')

现在,我需要预取其关联并使用 prefetch_related方法将其附加到序列化程序中。

Now, I need to prefetch its association and append it in the serializer using "prefetch_related" method.

Organizations.objects.prefetch_related('locations').order_by('name')

在这里,我似乎找不到限制的方法使用 prefetch_related之后的字段。

Here, I cannot seem to find a way to limit the fields after using "prefetch_related".

我尝试了以下操作,但是这样做时序列化程序看不到关联的位置。

I have tried the following, but on doing so serializer does not see the associated "locations".

Organizations.objects.prefetch_related('locations').values("id", "name").order_by('name')

模型骨架:

class Organizations(models.Model):
    name = models.CharField(max_length=40)

class Location(models.Model):
    name = models.CharField(max_length=50)
    organization = models.ForeignKey(Organizations, to_field="name", db_column="organization_name", related_name='locations')

    class Meta:
        db_table = u'locations'


推荐答案

使用 only()如果您担心应用程序的性能,可以限制检索到的字段数。请参见参考

Use only() to limit number of fields retrieved if you're concerned about your app performances. See reference.

这篇关于如何结合Django“ prefetch_related”和“值”方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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