简体   繁体   English

django多对多字段管理页面

[英]django many-to-many field admin page

I have a many-to-many field between two models in Django. 我在Django中的两个模型之间有一个多对多字段。 I however only see a form field in one of the models on the admin page. 但是,我在管理页面上仅在其中一个模型中看到一个表单字段。 I tried adding a many-to-many field in the second model, and although this added a form field in the admin page, the two form fields were not synchronized (so changing the value on one form field doesn't affect the other one). 我尝试在第二个模型中添加一个多对多字段,尽管这在管理页面中添加了一个表单字段,但是两个表单字段未同步(因此更改一个表单字段的值不会影响另一表单字段)。 Is there a way to have a many-to-many relationship and have two form fields in the admin page and both are synchronized? 有没有一种方法可以建立多对多关系,并且在管理页面中有两个表单域,并且两者都已同步?

There is an open source Django app called django-admin-extend which addresses the issue of bidirectional many-to-many fields using add_bidirectional_m2m and _get_bidirectional_m2m_fields. 有一个名为django-admin-extend的开源Django应用程序,它使用add_bidirectional_m2m和_get_bidirectional_m2m_fields解决了双向多对多字段的问题。 It can be installed via pip. 可以通过pip安装。

https://github.com/kux/django-admin-extend https://github.com/kux/django-admin-extend

https://pypi.python.org/pypi/django-admin-extend https://pypi.python.org/pypi/django-admin-extend

If you define the m2m relationship in both models, and set the "through" attribute of one to be equal to the "through" of the other, you get access to the m2m relationship from both sides, and get to see it from both admin pages. 如果您在两个模型中都定义了m2m关系,并且将一个模型的“直通”属性设置为与另一个模型的“直通”属性相等,则可以从两侧访问m2m关系,并可以从两个管理员那里查看页面。

class Test1(models.Model):
    tests2 = models.ManyToManyField('Test2', blank=True)

class Test2(models.Model):
    tests1 = models.ManyToManyField('Test1', through=Test1.tests2.through, blank=True)

as seen in https://code.djangoproject.com/ticket/897 https://code.djangoproject.com/ticket/897所示

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

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