Django 管理中的 raw_id_fields 和 ManyToMany
我想在管理中的多对多关系上使用 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'>
我不清楚我在这里做错了什么。感谢您的建议。
I want to use raw_id_fields on a ManyToMany relationship in the admin, and I want each related object to show up on its own row (as opposed to a comma-separated list in a single field, which is the default behavior). Following examples spotted in the wild, it seems like I should be able to do this:
# 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)
But that generates the error:
<class 'bucket.models.Profile'> has no ForeignKey to <class 'bucket.models.Profile'>
I'm not clear what I'm doing wrong here. Thanks for suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您为
InlineAdmin
设置了错误的模型因为您定义的关注者模型是
User
,而不是Profile
。查看文档 我想说你应该尝试:
并且
Looks like you are setting the wrong model for your
InlineAdmin
as the model for followers you are defining is
User
and notProfile
.Looking at the docs I'd say you should try:
and
在 m2m 连接的内联中,您应该使用
through
表,对于raw_id_fields
设置,您应该使用该through
表中的字段 - 该表中的字段可以是名称与您期望的不同。您需要进入 sqlite3/psql 等终端来查看
through
表架构,并为raw_id_fields
使用适当的字段。In inline for m2m connection you should use
through
table and forraw_id_fields
setting you should use fields from thatthrough
table - inside this table fields can be name different as you expect.You need goes to sqlite3/psql etc. terminal to see
through
table schema and use propper field forraw_id_fields
.