如何在 SubFactory (Django) 中包含多对多字段?

How to include Many to Many Field in SubFactory (Django)?

我有两个模型:ProjectTag。在 Project 中有 ManyToManyField: project_tags 我已经为他们两个写了工厂。问题是我不知道如何将 TagFactory 包含到 ProjectFactory

我试过:

project_tags = factory.SubFactory(TagFactory)

错误:

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use project_tags.set() instead

还有:

Project.project_tags.set()

错误:

AttributeError: 'ManyToManyDescriptor' object has no attribute 'set'

简单的解决方法是通过factory.RelatedFactory or factory.RelatedFactoryList:

class ProjectFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Project

    tags = factory.RelatedFactoryList(
        TagFactory,
        size=4,
    )