自动为OneToOne字段选择相关 [英] Automatically select related for OneToOne field

查看:78
本文介绍了自动为OneToOne字段选择相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django项目中,我为每个django用户都有一个配置文件,该配置文件与一个信息模型相关。两种关系都是OneToOne。由于大多数时候我都同时为用户使用Profile和Info模型,因此我希望默认情况下将其选中,因此不会再次访问数据库。有什么方法可以使用Django身份验证来做到这一点?

In my Django project I have a Profile for each django User, and the Profile is related to an Info model. Both relationships are OneToOne. Since most of the time I am using both the Profile and the Info models for a user, I would like those to be selected by default so I don't hit the database again. Is there any way to do this using Django authentication?

推荐答案

我知道这已经存在了一段时间了,但是我要添加我的解决方案,以防其他人面临类似情况。
Django(从v1.8甚至v1.7起)允许您自定义经理(查询时使用的.objects)

I know this has been here for a while but I am adding my solution in case someone else faces a similar situation. Django (as of v1.8 and even v1.7) allows you to customized the managers ( .objects used when querying )

您可以为Profile创建一个这样的经理:

You could have a manager like this for Profile:

class ProfileManager(models.Manager):
    def get_queryset(self):
        return super(ProfileManager,self).get_queryset().select_related('user')

然后在模型中:

class Profile(models.Model):
    user = models.OneToOneField(
        User,
        primary_key=True,
        on_delete=models.CASCADE
    )

    # ... other fields 

    # the manager
    objects = ProfileManager()

    # ...

然后您在个人资料上进行的所有查询也会自动选择相关用户。

Then all your queries on Profile will automatically select the related user too.

您可以将此代码扩展到in也包含信息模型。

这篇关于自动为OneToOne字段选择相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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