本文介绍了Django,Wagtail管理员:使用"through"处理多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个带有 through 表的模型,例如:

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:

这个错误对我来说很有意义.我应该保存AB实例.我只是不确定在Wa中实现此目标的最佳方法是什么.

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.

推荐答案

您需要的是InlinePanel: http://docs.wagtail.io/zh/v2.0.1/getting_started/tutorial.html#images

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'),
    ]

这篇关于Django,Wagtail管理员:使用"through"处理多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 00:21