访问用户profi的反向关系

2024-09-27 23:26:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的应用程序中,同时有0个或1个配置文件的用户。 随着时间的推移,我的项目有许多不同的配置文件

从profileX访问用户很容易:profile_x_object.user 但是相反的关系呢? 我想找到最好的通用方法来创建从用户到其配置文件的关系

现在,我创建了一个名为profile的属性来满足这个目的。 它的工作,但它需要为每一个新的配置文件,我添加了一段时间更新。 有没有更好的办法

以下是我的代码:

class User:
   # ...

    @property
    def profile(self):
        if hasattr(self, 'profilea'):
            return self.profilea
        if hasattr(self, 'probileb'):
            return self.probileb

class BaseProfile(models.Model):

    class Meta:
        abstract = True

    user = models.OneToOneField(settings.AUTH_USER_MODEL)

class ProfileA(BaseProfile, models.Model):
    # ...

class ProfileB(BaseProfile, models.Model):
    # ...

Tags: 用户selfmodelreturnif关系models配置文件
1条回答
网友
1楼 · 发布于 2024-09-27 23:26:31

您可以使用model meta api并检查其相关模型为BaseProfile子类的1对1字段:

from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields.related import OneToOneRel
from django.utils.functional import cached_property

class User(Abs...User):
    # ...

    @cached_property
    def profile(self):
        for f in User._meta.get_fields():
            if isinstance(f, OneToOneRel) and issubclass(f.related_model, BaseProfile):
                try:
                    return getattr(self, f.name)
                except ObjectDoesNotExist:
                    pass
        # no profile found
        return None

相关问题 更多 >

    热门问题