如何为多对多字段构建 YAML 数据(Python 3.9,Django 3)?

How do I structure YAML data for a many-to-many field (Python 3.9, Django 3)?

我正在使用 Python 3.9 和 Django 3.0。我定义了以下模型。第二个与第一个具有多对多关系...

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False)

    objects = CoopTypeManager()

    class Meta:
        # Creates a new unique constraint with the `name` field
        constraints = [models.UniqueConstraint(fields=['name'], name='coop_type_unq')]

...
class Coop(models.Model):
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    types = models.ManyToManyField(CoopType, blank=False)
    addresses = models.ManyToManyField(Address)
    enabled = models.BooleanField(default=True, null=False)
    phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone')
    email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email')
    web_site = models.TextField()

对于子实体,我定义了这个“get_by_natural_key”方法(名称字段)...

class CoopTypeManager(models.Manager):

    def get_by_natural_key(self, name):
        return self.get_or_create(name=name)[0]

如何构造我的 YAML 以便我可以创建具有多种类型的 Coop?当只有一种类型时,此 YAML 工作正常

  pk: 243
  fields:
    name: "Dill Pickle Food Co-op"
    types:
    - ['food coop']

但是当我尝试添加不止一种类型时,就像这样...

  pk: 243
  fields:
    name: "Dill Pickle Food Co-op"
    types:
    - ['store', 'food coop']

我收到这个错误...

django.core.serializers.base.DeserializationError: Problem installing fixture '/tmp/seed_data.yaml': get_by_natural_key() takes 2 positional arguments but 3 were given: (directory.coop:pk=243) field_value was '['store', 'food coop']'

您使用两个项目执行此操作:

pk: 243
  fields:
    name: "Dill Pickle Food Co-op"
    types:
    - <b>['food coop']</b>
    - <b>['store']</b>

列表列出了类型的自然键。因此,您不能在此处使用两个值,因为只有 name.