In FactoryBoy, how do I set a many-to-many field in my factory?

痴心易碎 提交于 2020-06-17 09:34:06

问题


I'm using Django 2.2 and FactoryBoy to attempt to create some factories to produce the following models ...

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)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()

Here is my factory for creating the Coop object ...

class CoopFactory(factory.DjangoModelFactory):
    """
        Define Coop Factory
    """
    class Meta:
        model = Coop

    name = "test model"
    address = factory.SubFactory(AddressFactory)
    enabled = True
    phone = "312-999-1234"
    email = "test@hello.com"
    web_site = "http://www.hello.com"

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

        if extracted:
            # A list of types were passed in, use them
            for type in extracted:
                self.types.add(type)
        else:
            type = CoopTypeFactory()
            self.types.set( (type) )

This is my test ...

@pytest.mark.django_db
def test_coop_create(self):
    """ Test customer model """    # create customer model instance
    coop_from_factory = CoopFactory()
    self.assertIsNotNone(coop_from_factory)

    coop = Coop.objects.create(name='test', address=coop_from_factory.address)
    self.assertIsNotNone(coop)

However, it doesn't seem to like this line

self.types.set( (type) )

from the factory, because the test dies with the below error. What is the proper way to get my factory to work with a many-to-many field?

    ======================================================================
ERROR: test_coop_create (tests.test_models.ModelTests)
Test customer model
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_models.py", line 34, in test_coop_create
    coop_from_factory = CoopFactory()
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 46, in __call__
    return cls.create(**kwargs)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 564, in create
    return cls._generate(enums.CREATE_STRATEGY, kwargs)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 141, in _generate
    return super(DjangoModelFactory, cls)._generate(strategy, params)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 501, in _generate
    return step.build()
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/builder.py", line 299, in build
    context=postgen_context,
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/declarations.py", line 623, in call
    instance, create, context.value, **context.extra)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/factories.py", line 96, in types
    self.types.set( (type) )
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 1002, in set
    objs = tuple(objs)
TypeError: 'CoopType' object is not iterable

来源:https://stackoverflow.com/questions/61922901/in-factoryboy-how-do-i-set-a-many-to-many-field-in-my-factory

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