Django:如何正确使用ManyToManyField与Factory Boy Factories和Serializers?

问题描述 投票:2回答:1

问题

我使用的模型类Event包含一个可选的ManyToManyField到另一个模型类,User(不同的事件可以有不同的用户),工厂类EventFactory(使用Factory Boy库)和序列化器EventSerializer。我相信我已经按照工厂制作和序列化的文档,但收到错误:

ValueError:“<Event:Test Event>”需要具有字段“id”的值,才能使用此多对多关系。

我知道两个模型实例必须在链接它们之前在ManyToMany中创建,但我看不到添加的位置!

问题

有人可以用我尚未做过的方式澄清如何使用模型,工厂男孩和序列化器正确使用ManyToManyField吗?

设置

这是我的代码:

models.朋友

@python_2_unicode_compatible
class Event(CommonInfoModel):
    users = models.ManyToManyField(User, blank=True, related_name='events')
    # other basic fields...

factories.朋友

class EventFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Event

    @factory.post_generation
    def users(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of users were passed in, use them
            # NOTE: This does not seem to be the problem. Setting a breakpoint                     
            # here, this part never even fires
            for users in extracted:
                self.users.add(users)

serialize认识.朋友

class EventSerializer(BaseModelSerializer):
    serialization_title = "Event"
    # UserSerializer is a very basic serializer, with no nested 
    # serializers
    users = UserSerializer(required=False, many=True)

    class Meta:
        model = Event
        exclude = ('id',)

test.朋友

class EventTest(APITestCase):
@classmethod
def setUpTestData(cls):
    cls.user = User.objects.create_user(email='[email protected]',  
    password='password')

def test_post_create_event(self):
    factory = factories.EventFactory.build()
    serializer = serializers.EventSerializer(factory)

    # IMPORTANT: Calling 'serializer.data' is the exact place the error occurs!
    # This error does not occur when I remove the ManyToManyField
    res = self.post_api_call('/event/', serializer.data)

Version Info

  • Django 1.11
  • Python 2.7.10

感谢您提供任何帮助!

django django-serializer manytomanyfield factory-boy
1个回答
1
投票

关于错误:似乎缺少id是由于使用.build()而不是.create()(或只是EventFactory())。前者不保存模型,因此它没有得到id值,而后者确实(参考factory docsmodel docs)。

我怀疑序列化程序仍然期望该对象具有id,即使多对多关系是可选的,因为它不能强制执行没有id的潜在关系。

但是,实际任务可能有一个更简单的解决方案。上述方法是一种生成传递给post_api_call()的POST数据的方法。如果这个数据是手动创建的,那么工厂和序列化器都变得不必要了。从测试角度来看,显式数据方法甚至可能更好,因为您现在可以看到必须产生预期结果的确切数据。而对于工厂和序列化器方法,它在测试中实际使用的内容中更为隐含。

© www.soinside.com 2019 - 2024. All rights reserved.