简体   繁体   English

Django将ManyToMany关系添加到管理员用户表单

[英]Django Add ManyToMany Relationship to Admin User Form

I'm using the django admin feature as the backend administration for my site. 我正在使用django管理员功能作为网站的后端管理。 It seems to work perfectly, out of the box for my needs, except for one thing. 除一件事外,它似乎可以完美地工作,可以满足我的需要。 One of my models has a many-to-many relationship with a User. 我的一个模型与用户之间存在多对多关系。 Here is the model: 这是模型:

class Facility(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.TextField()     
    users = models.ManyToManyField(User)    
    def __str__(self):
        return str(self.id)    

I've gotten it to let me add users to the facility on the facility page, but since the Admin form is built in, I don't know how to modify it. 我已经有了它,可以将用户添加到设施页面上的设施,但是由于内置了管理表单,因此我不知道如何修改它。 I found something that looked like what I want on SO: 我发现了一些我想要的东西:

admin.site.unregister(User)

class MyUserAdmin(UserAdmin):
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2')}
        ),
    )

admin.site.register(User, MyUserAdmin)

I tried swapping out email for facility or facilities or facilitys , but it seemed pretty obvious that that wouldn't work, and of course it did not. 我试着换出电子邮件facilityfacilitiesfacilitys ,但它似乎很明显,这是行不通的,当然它没有。 Any one have any advice? 有人有什么建议吗?

In django this feature names related_name or "back reference" in SQLAlchemy. 在Django中,此功能在SQLAlchemy中命名为related_name或“反向引用”。 As you can see in docs : 正如您在docs中看到的:

If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. 如果模型具有ForeignKey,则外键模型的实例将有权访问Manager,该Manager返回第一个模型的所有实例。 By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. 默认情况下,此Manager名为FOO_set,其中FOO是源模型名称,小写。

So, in your case you should use facility_set or redefine related_name on users ManyToMany field in Facility model. 因此,在您的情况下,应在Facility模型中的users ManyToMany字段上使用facility_set或重新定义related_name

BTW, @schillingt : suggestion to use InlineModelAdmin much more easy and elegant than anything else. 顺便说一句, @schillingt :建议使用InlineModelAdmin比其他任何工具都更加轻松和优雅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM