如何使用TaggableManager字段为模型创建Factory-Boy工厂

时间:2014-11-11 13:46:40

标签: django django-taggit factory-boy

如何从django-taggit在Factory-Boy到TaggableManager中创建一个字段?

以下不起作用:

首先:

class ExperimentFactory(factory.DjangoModelFactory):
    class Meta:
        model = Experiment
        django_get_or_create = ('owner', 'name', 'start_date', 'stop_date', )

    owner = factory.SubFactory(UserFactory)
    name = factory.Sequence(lambda n : 'Experiment %s' % n)

    start_date = fuzzy.FuzzyDate(start_date=datetime.date(2003, 2, 1), 
                                     end_date = datetime.date.today() + timedelta(days=4*52*7+5))

    tags = [u'abc, cde', u'xzy']

错误是:TypeError:'tags'是此函数的无效关键字参数

第二:(与factory.post_generation)。所以不是最后一行就是

@factory.post_generation
def post_tags(self, create, extracted, **kwargs):
    self.tags = [u'abc, cde', u'xzy']
    # self.save() # This does not have any effects

我得到Experiment.objects.get(pk=1).tags的结果是[]

了解一些细节:

TestCase中对象的测试是:

experiment = ExperimentFactory(owner = self.user)
saved_experiment = Experiment.objects.get(name=experiment.name) 

self.assertEquals(len(experiment.tags), len(saved_experiment.tags.all())) # AssertError: 2 != 0
self.assertItemsEqual(experiment.tags, saved_experiment.tags.all())

奇怪的是,在self.experiments中设置了标签。调用post_tags()方法。

模型是:

class Experiment(models.Model):
     owner = models.ForeignKey(User, related_name='experiments') 

     name = models.CharField(max_length=32, default='')
     start_date = models.DateField()

     tags = TaggableManager()

2 个答案:

答案 0 :(得分:2)

终于找到了解决方案:

@factory.post_generation
def post_tags(self, create, extracted, **kwargs):
    self.tags.add(u'abc, cde', u'xzy')

答案 1 :(得分:1)

对于其他任何想要使用Factory Boy和django-taggit的更一般化示例的人来说,Factory Boy文档include a Many-to-Many example是有用的。所以:

import factory

from myapp.models import Experiment


class ExperimentFactory(factory.DjangoModelFactory):
    class Meta:
        model = Experiment

    # other fields here

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

        if extracted:
            # A list of tags were passed in, use them.
            for tag in extracted:
                self.tags.add(tag)

然后你可以这样做:

from myapp.factories import ExperimentFactory

ExperimentFactory(name='A Name', tags=['Tag 1', 'Tag 2', 'Another tag',])

请注意,只有当您执行ExperimentFactory.build()或其同义词ExperimentFactory.create()时,才会创建ExperimentFactory()标记。