【问题标题】:Foreign Key Relations between 2 apps and User model2个应用程序和用户模型之间的外键关系
【发布时间】:2013-03-06 17:08:03
【问题描述】:

我有一个应用程序,其中模型扩展了用户模式。

class ExtendedUser (models.Model):
    user = models.ForeignKey(User)
    favorite_color = models.CharField(...
    #...

我有另一个应用程序,它也具有用户模型的外键。

我想知道如何访问与特定用户相关的所有信息?

当我尝试建立反向关系时(我认为)我的问题出现了,这是我尝试的:

>>from django.contrib.auth.models import User
>>from firstapp.models import ExtendedUser

>>a = User.objects.get(pk=1)
>>a
<User: username1>
>>b = a.favorite_color
AttributeError: 'User' object has no attribute 'favorite_color'
>>c = ExtendedUser.objects.get(pk=1)
>>c
<User: username1>
>>c.favorite_color
<Favorite_color: blue>

问题是当我在“a”上时,我无法访问用户的扩展模型信息,例如“favorite_color”,而当我在“c”上时,我无法访问用户模型原生信息,例如电子邮件或烫发。有没有办法做到这一点?

还有,

有没有一种方法可以让我选择一个用户 ID 并查看与该对象相关的所有字段(来自所有模型和应用程序)?

【问题讨论】:

    标签: django django-models foreign-keys


    【解决方案1】:

    但这根本不是“扩展用户模型”。您通过 ForeignKey 引用了一个完全不同的模型。我不知道您为什么会期望 favorite_color 突然成为 User 模型上的一个属性。

    使用 OneToOneField 代替 ForeignKey(这意味着每个用户有多个 ExtendedUser)。然后就可以直接跟关系了:

    user = User.objects.get(pk=1)
    print user.extendeduser.favorite_color
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      相关资源
      最近更新 更多