使用 Django 的 ManyToManyField 和预定义的中间模型

发布于 2024-10-04 03:40:20 字数 973 浏览 0 评论 0原文

这是我的模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云醉月微眠 2024-10-11 03:40:20

您不能在 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 field admins or you use an inline admin there to allow easy creation of new Users objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文