2015-08-14 90 views
7

问题Django admin ManyToMany inline "has no ForeignKey to" error的答案是指Django​​文档。鉴于那里的车型有:Django管理员多对多颠倒?

class Person(models.Model): 
    name = models.CharField(max_length=128) 

class Group(models.Model): 
    name = models.CharField(max_length=128) 
    members = models.ManyToManyField(Person, related_name='groups') 

和在线管理类:

class MembershipInline(admin.TabularInline): 
    model = Group.members.through 

class PersonAdmin(admin.ModelAdmin): 
    inlines = [MembershipInline,] 

class GroupAdmin(admin.ModelAdmin): 
    inlines = [MembershipInline,] 
    exclude = ('members',) 

...允许组成员从个人页面从组页面进行管理,但没有。但是如果管理员只想从组页面管理成员呢?摆脱exclude行将允许两个页面管理关系,但Django文档(可能不正确)说“你必须告诉Django的管理员不要显示这个小部件”。他们可能意味着你“应该”告诉Django的管理员不要显示它 - 如果你不这样做会有什么不好的,但这是多余的。

因此,在不更改模型的情况下,是否可以从Person页面而不是从Group页面中排除会员窗口小部件?这两个明显的尝试:

class PersonAdmin(admin.ModelAdmin): 
    inlines = [MembershipInline,] 
    exclude = ('Group.members',) 

class PersonAdmin(admin.ModelAdmin): 
    inlines = [MembershipInline,] 
    exclude = ('groups',) 

(第二使用从模型中related_name)失败,出现错误:

'PersonAdmin.exclude' refers to field 'groups' that is missing from the form. 

是,该模型可以改变放Person下的ManyToManyField。但是由于它是一种对称关系,没有逻辑上的原因,为什么它不能从Person或Group(而不是两个)进行管理,而无需更改数据库模式。 Django Admin是否可以通过组页面管理组成员身份并将其从个人页面中排除?

回答

0

你不给此要求的引用:

the Django documentation (probably incorrectly) says "you must tell Django’s admin to not display this widget".

所以我只能参考current (1.10) documentation for Django。目前,它说的ManyToMany fields in the admin

Django displays an admin widget for a many-to-many field on the model that defines the relation (in this case, Group). If you want to use an inline model to represent the many-to-many relationship, you must tell Django’s admin to not display this widget - otherwise you will end up with two widgets on your admin page for managing the relation.

所以,在回答您的正确说法:

But since it is a symmetric relationship, there is no logical reason why it could not be managed from either Person or Group (but not both) without having to change the database schema.

的原因是,许多一对多的关系在某处定义;您已选择在组模型中定义它,以确定默认的管理行为。如果你想移动它,那么你需要做一个数据库迁移来实现这一点。

另一方面,如果您希望记录的行为有所不同,请更改而不是更改您的使用方法 - 您似乎无法提出适合于StackOverflow的问题。更好地报告the project's bug tracker中的程序错误,要求更改软件的行为。

+1

当然,我可以重新定义模式并迁移数据库,如原始问题中所述。管理界面没有固有的技术理由允许从一端管理对称关系,而不是从另一端管理对等关系 - 一个*应该*能够管理成员所属的组或成员列表,无论定义关系的地方。你只是重申了记录的限制,没有提供它的存在的理由。 – Dave