Django模型中的Python factory_boy库m2m? [英] Python factory_boy library m2m in Django model?

查看:351
本文介绍了Django模型中的Python factory_boy库m2m?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 factory_boy 在我的测试中创建灯具。
Factory_boy 仅提及关于 SubFactory 的文档,可以像 ForeignKey 字段在模型中。然而,ManyToMany协会没有什么。如果我有一个Post模型,我该如何去创建一个工厂?

I'm currently using factory_boy for creating fixtures in my tests. Factory_boy docs only mentioned about SubFactory which could act like a ForeignKey field in a model. However, there was nothing on ManyToMany association. If I had a following Post model, how would I go about creating a factory for it?

class Post(models.Model):
    title = models.CharField(max_length=100)
    tags = models.ManyToManyField('tags.Tag')

class PostFactory(factory.Factory):
    FACTORY_FOR = Post

    title = 'My title'
    tags = ???


推荐答案

post_generation钩子 - 我假设你使用较新版本的 factory_boy

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)

请注意,您可以使用 PostFactory(tags__field ='some fancy default text'),但是我建议使用Sequences ...创建好的 TagFactory

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

你应该可以绑定 PostFactory(tags = Tag.objects.filter())但是这部分没有被测试...

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

这篇关于Django模型中的Python factory_boy库m2m?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆