使用 Django 的 ManyToManyField 和预定义的中间模型
这是我的模型:
class Groups(models.Model):
group_id = models.AutoField(primary_key=True)
group_name = models.CharField(max_length=20,db_index=True)
#Some other fields
admins = models.ManyToManyField(Users, through='GroupAdmin')
class Users(models.Model):
user_id = models.AutoField(primary_key=True)
#Some other fields...
name_text = models.CharField(max_length=20)
class GroupAdmin(models.Model):
group_admin_id = models.AutoField(primary_key=True)
user = models.ForeignKey(Users)
group = models.ForeignKey(Groups)
然后我定义了这个 ModelAdmin
class GroupAdminAdmin(admin.ModelAdmin):
filter_horizontal = ['user']
admin.site.register(GroupAdmin, GroupAdminAdmin)
由于某些原因,我仍然无法弄清楚,每当我尝试使用它时,我的网页上都会出现以下错误。
ImproperlyConfigured at /admin/mysite
'GroupAdminAdmin.filter_horizontal[0]' must be a ManyToManyField.
我做错了什么?
Here are my models:
class Groups(models.Model):
group_id = models.AutoField(primary_key=True)
group_name = models.CharField(max_length=20,db_index=True)
#Some other fields
admins = models.ManyToManyField(Users, through='GroupAdmin')
class Users(models.Model):
user_id = models.AutoField(primary_key=True)
#Some other fields...
name_text = models.CharField(max_length=20)
class GroupAdmin(models.Model):
group_admin_id = models.AutoField(primary_key=True)
user = models.ForeignKey(Users)
group = models.ForeignKey(Groups)
Then I have this ModelAdmin
defined
class GroupAdminAdmin(admin.ModelAdmin):
filter_horizontal = ['user']
admin.site.register(GroupAdmin, GroupAdminAdmin)
For some reasons that I'm still unable to figure out I keep getting the following error on my web page whenever I try to work with this.
ImproperlyConfigured at /admin/mysite
'GroupAdminAdmin.filter_horizontal[0]' must be a ManyToManyField.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能在
ForeignKey
上使用过滤器水平小部件(这几乎没有任何意义,因为它只能引用一个对象,而小部件的主要目标是轻松选择多个对象)。您可以在
Groups
的管理员中将其用于admins
字段,或者使用内联管理员来轻松创建新的Users
对象。You cannot user the filter horizontal widget on a
ForeignKey
(which would hardly make any sense since it can only reference one object, while the widget's main goal is to easily select more than one object).You could use it on your admin for
Groups
for the fieldadmins
or you use an inline admin there to allow easy creation of newUsers
objects.