Dav*_*ave 7 python django django-models django-admin
回答问题Django管理员ManyToMany内联"没有ForeignKey to"错误是指Django Admin文档.给出的模型有:
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')
Run Code Online (Sandbox Code Playgroud)
内联管理类是:
class MembershipInline(admin.TabularInline):
model = Group.members.through
class PersonAdmin(admin.ModelAdmin):
inlines = [MembershipInline,]
class GroupAdmin(admin.ModelAdmin):
inlines = [MembershipInline,]
exclude = ('members',)
Run Code Online (Sandbox Code Playgroud)
...允许从"个人"页面管理组成员资格,但不能从"组"页面管理.但是,如果管理员只想从"组"页面管理成员,该怎么办?摆脱这一exclude行将允许两个页面管理关系,但Django文档(可能不正确)说"你必须告诉Django的管理员不显示这个小部件".他们可能的意思是你"应该"告诉Django的管理员不要显示它 - 如果你不这样做会发生什么不好,但这是多余的.
因此,如果不更改模型,是否可以从"个人"页面而不是"组"页面中排除成员资格窗口小部件?两个明显的尝试:
class PersonAdmin(admin.ModelAdmin):
inlines = [MembershipInline,]
exclude = ('Group.members',)
Run Code Online (Sandbox Code Playgroud)
和
class PersonAdmin(admin.ModelAdmin):
inlines = [MembershipInline,]
exclude = ('groups',)
Run Code Online (Sandbox Code Playgroud)
(使用related_name模型中的第二个)失败并显示错误:
'PersonAdmin.exclude' refers to field 'groups' that is missing from the form.
Run Code Online (Sandbox Code Playgroud)
是的,该模型可以改变把ManyToManyField下Person.但由于它是一种对称关系,因此无需更改数据库模式就无法从Person或Group(但不是两者)管理它的逻辑原因.Django Admin可以从组页面管理组成员身份并将其从人员页面中排除吗?
big*_*ose -1
您没有提供此声明的参考:
\n\n\n\n\nDjango 文档(可能不正确)说“您必须告诉 Django\xe2\x80\x99s 管理员不要显示此小部件”。
\n
所以我只能参考Django 的当前(1.10)文档。目前它提到了管理中的ManyToMany字段:
\n\n\n\n\nDjango 在定义关系的模型上显示多对多字段的管理小部件(在本例中为
\nGroup)。如果你想使用内联模型来表示多对多关系,你必须告诉 Django\xe2\x80\x99s admin 不要显示这个小部件 - 否则你最终会在管理页面上出现两个小部件来管理关系。
因此,针对您的正确说法:
\n\n\n\n\nBut 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.
\n
the reason is that the many-to-many relationship has to be defined somewhere; you have chosen to define it on the Group model, so that determines the default admin behaviour. If you want to move it, then you\'ll need to do a database migration to make that happen.
\n\nIf, on the other hand, you want this documented behaviour to be different without changing your use of it \xe2\x80\x94 you don\'t seem to be asking a question that fits at StackOverflow. Better to report a bug with the program at the project\'s bug tracker, asking for a change in the software\'s behaviour.
\n| 归档时间: |
|
| 查看次数: |
1203 次 |
| 最近记录: |