Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django循环引用_Python_Django - Fatal编程技术网

Python Django循环引用

Python Django循环引用,python,django,Python,Django,我遇到过很多需要调整models.py文件以避免循环依赖的情况 这是最新的例子。我有registration/models.py,如下所示(为了简单起见,我删除了绝大多数代码): 后来我了解到UserProfile模型(在user_profile.models.py中定义)应该指向用户,而不是当前的方式 (最初,我在用户模型中有一个与图片模型链接的profile_picture列。我注意到每当我删除图片记录时,用户记录就开始消失。这是由于级联删除。我反转外键,以便图片指向用户,并希望对UserP

我遇到过很多需要调整models.py文件以避免循环依赖的情况

这是最新的例子。我有registration/models.py,如下所示(为了简单起见,我删除了绝大多数代码):

后来我了解到UserProfile模型(在user_profile.models.py中定义)应该指向用户,而不是当前的方式

(最初,我在用户模型中有一个与图片模型链接的profile_picture列。我注意到每当我删除图片记录时,用户记录就开始消失。这是由于级联删除。我反转外键,以便图片指向用户,并希望对UserProfile执行相同的操作。)

不幸的是,如果用户_profile/models.py导入registration/models.py,那么registration/models.py将无法再导入用户_profile/models.py,因此无法再使用UserProfile管理器在其管理器内创建UserProfile记录

我知道这两个模型是紧密耦合的。。。它们应该在同一个应用程序中吗?我如何防止此类问题。我曾看到第三方框架将其管理者分割成不同的文件,但如果我这样做,我仍然会遇到同样的问题。我该怎么做

我想我只是需要一些指导。我对大型应用程序几乎没有经验,以前也没有用复杂的方式管理依赖关系

谢谢你的帮助, 尼克


编辑:我应该注意,我知道我可以通过在_create_user函数中导入user_profile.models来解决所有这些问题,但据我所知,这是一种糟糕的做法。

您是否覆盖django用户模型,但不扩展它?我应该提到这一点。我正在覆盖模型。我发现,通过将所有常用字段放在覆盖的用户模型中,而不是通过OneToOne外键的扩展模型中,我获得了巨大的性能提升。然后设置和不太常用的字段出现在UserProfile中。有趣的是,通常我会通过创建CustomUser模型来扩展用户模型,指向用户模型并更改
AUTH\u User\u模型
。或者,创建一个完整的新CustomUser模型,继承所有manager的内容,包括
AbstractBaseUser
。目前,您正在覆盖现有的用户模型,添加新字段,但也使用一对一的UserProfile模型对其进行扩展,在我看来,听起来不对,而且它肯定是紧密耦合的,这使得它不太可能成为未来的证明。如果我是你,我可能会用一个CustomUser模型重写整个过程,其中包含你需要的所有字段,记住你还需要处理superuser等。你真的扩展了
用户
模型并覆盖了它,你真的得到了性能改进吗?正如我所知,Django不使用
SELECT*
查询,它使用类似
selectid。。。。用户名
from user_profile.models import UserProfile

class UserManager(BaseUserManager):

@transaction.atomic()  # We definitely do not want to create a User record without a UserProfile
def _create_user(self, email, **kwargs):

    user_profile = UserProfile.objects.create_user_profile(first_name, last_name)

    email = self.normalize_email(email)
    user = self.model(email=email,
                      **kwargs
                      )

    user.set_password(password)
    user.save()

    return user


class User(AbstractBaseUser, PermissionsMixin, TimeStampedModel):
     email = models.EmailField('email address',
                          max_length=user_model_settings.get('EMAIL_MAX_LENGTH'),
                          unique=True,
                          blank=False
                          )

    user_profile = models.OneToOneField(UserProfile,
                                    null=False,
                                    )