[Solved]-Python factory_boy library m2m in Django model?

11👍

What about post_generation hook – I assume You use newer version of factory_boy?

import random
import factory

class PostFactory(factory.Factory):
    FACTORY_FOR = Post
    title = factory.Sequence(lambda n: "This is test title number" + n)
    @factory.post_generation(extract_prefix='tags')
    def add_tags(self, create, extracted, **kwargs):
        # allow something like PostFactory(tags = Tag.objects.filter())
        if extracted and type(extracted) == type(Tag.objects.all()):
            self.tags = extracted
            self.save()
        else:
            if Tag.objects.all().count() < 5:
                TagFactory.create_batch(5, **kwargs)
            for tag in Tag.objects.all().order_by('?')[:random.randint(1, 5)]:
                self.tags.add(tag)

Note that You can use PostFactory(tags__field = 'some fancy default text'), but I recommend to create good TagFactory with Sequences …

You should be able to bind PostFactory(tags = Tag.objects.filter()) but this part is not tested …

👤lechup

7👍

You can override the _prepare classmethod:

class PostFactory(Factory):
    FACTORY_FOR = Post

    title = 'My title'

    @classmethod
    def _prepare(cls, create, **kwargs):
        post = super(PostFactory, cls)._prepare(create, **kwargs)
        if post.id:
            post.tags = Tag.objects.all()
        return post

Note that you can’t add tags to a post if the post doesn’t have an ID.

2👍

I did not test it, but what is the problem with:

class PostFactory(factory.Factory):
    FACTORY_FOR = Post
    title = 'My title'

class TagFactory(factory.Factory):
    FACTORY_FOR = Tag

post = PostFactory()
tag = TagFactory()
post.tags.add(tag)
👤Ale

Leave a comment