【问题标题】:raw_id_fields and ManyToMany in Django adminDjango admin 中的 raw_id_fields 和 ManyToMany
【发布时间】:2011-09-01 10:39:58
【问题描述】:

我想在管理中的多对多关系上使用 raw_id_fields,并且我希望每个相关对象都显示在自己的行上(而不是单个字段中的逗号分隔列表,这是默认行为)。按照在野外发现的例子,似乎我应该能够做到这一点:

# models.py
class Profile(models.Model):
    ...
    follows = models.ManyToManyField(User,related_name='followees')

# admin.py
class FollowersInline(admin.TabularInline):
    model = Profile
    raw_id_fields = ('follows',)
    extra = 1

class ProfileAdmin(admin.ModelAdmin):
    search_fields = ('user__first_name','user__last_name','user__username',)
    inlines = (FollowersInline,)

admin.site.register(Profile,ProfileAdmin)

但这会产生错误:

<class 'bucket.models.Profile'> has no ForeignKey to <class 'bucket.models.Profile'>

我不清楚我在这里做错了什么。感谢您的建议。

【问题讨论】:

    标签: django django-admin django-orm


    【解决方案1】:

    看来您为 InlineAdmin 设置了错误的模型 因为您定义的追随者模型是User 而不是Profile

    看看docs,我想说你应该试试:

    class FollowersInline(admin.TabularInline):
        model = Profile.follows.through
    

    class ProfileAdmin(admin.ModelAdmin):
        ....
        exclude = ('follows',)
        inlines = (FollowersInline,)
    

    【讨论】:

    • 感谢 Arie,但这给了我:“FollowersInline.raw_id_fields”指的是模型“Profile_follows”中缺少的字段“follows”。以下作为个人资料中的一个字段存在。
    • 嗯,我可能不完全理解您要做什么:您正在尝试关联FollowersProfiles,对吗?据我了解,您应该可以在您的InlineAdmin 上省略raw_id_fields = ('follows',)。然后您可以使用内联表单将Followers (User) 关联到Profiles
    • Followers 不是一个单独的模型 - “follows”是 Profile 模型上 m2m 字段的名称。我可以从 ProfileAdmin 中省略 follow,但是当我将 inlines = (FollowersInline,) 添加到 ProfileAdmin 时,我会收到上述两个错误之一,具体取决于我使用的是“model=Profile”还是“model=Profile.follows.through” .谢谢。
    • 嗯,我的意思是追随者,也就是用户(因为这是模型 follows 所涉及的)。据我了解,使用 Profile.follows.through 省略 raw_id 字段应该可以工作。但事实并非如此,我只能希望有人提出一个更好的主意。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2016-06-06
    • 2014-02-03
    • 2013-05-23
    • 2015-07-03
    • 2017-04-14
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多