在Foreignkey上进一步内联一个模块

时间:2012-03-22 13:30:31

标签: django django-models django-admin

我有这些模特:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    #etc

class Organization(models.Model):
    users = models.ManyToManyField(User, through=OrganizationUser, verbose_name=_('users'))
    #etc

class OrganizationUser(models.Model):
    organization = models.ForeignKey('Organization')
    user = models.ForeignKey(User)

我想向内联用户展示组织:

class UserOrganizationsInline(admin.TabularInline):
    model = OrganizationUser

class UserProfileAdmin(admin.ModelAdmin):
    inlines = [UserOrganizationsInline]

admin.site.register(UserProfile, UserProfileAdmin)

错误消息是:

<class 'customer.models.organization.OrganizationUser'> has no ForeignKey to <class 'customer.models.userprofile.UserProfile'>

我知道原因:组织将ForeignKey用于auth.User而不是modes.UserProfile。

如何在不改变模型的情况下完成这项工作。

1 个答案:

答案 0 :(得分:0)

粗略的想法(未经测试):将ForeignKey设置为UserProfile模型但反映user_id字段而不是主键。因此,您与UserProfile的关系与数据库中的值相同(User.id):

class OrganizationUser(models.Model):
    user = models.ForeignKey(UserProfile, to_field='user_id')