Django, Wagtail admin: handle many to many with `through`

て烟熏妆下的殇ゞ 提交于 2020-01-04 09:14:49

问题


I have 2 models with a through table such as:

class A(models.Model):
    title = models.CharField(max_length=500)
    bs = models.ManyToManyField(to='app.B', through='app.AB', blank=True)

    content_panels = [
        FieldPanel('title'),
        FieldPanel('fields'),    # what should go here?
    ]

class AB(models.Model):
    a = models.ForeignKey(to='app.A')
    b = models.ForeignKey(to='app.B')
    position = models.IntegerField()

    class Meta:
        unique_together = ['a', 'b']

I'm getting the following error when trying to save:

Cannot set values on a ManyToManyField which specifies an intermediary model.

That error makes sense to me. I should save AB instances instead. I'm just unsure what's the best way to achieve that in Wagtail.


回答1:


What you need is an InlinePanel: http://docs.wagtail.io/en/v2.0.1/getting_started/tutorial.html#images

from wagtail.admin.edit_handlers import FieldPanel, InlinePanel
from wagtail.core.models import Orderable
from modelcluster.fields import ParentalKey

# the parent object must inherit from ClusterableModel to allow parental keys;
# this happens automatically for Page models
from modelcluster.models import ClusterableModel

class A(ClusterableModel):
    title = models.CharField(max_length=500)

    content_panels = [
        FieldPanel('title'),
        InlinePanel('ab_objects'),
    ]

class AB(Orderable):
    a = ParentalKey('app.A', related_name='ab_objects')
    b = models.ForeignKey('app.B')
    panels = [
        FieldPanel('b'),
    ]


来源:https://stackoverflow.com/questions/50209851/django-wagtail-admin-handle-many-to-many-with-through

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!