3

如何从 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' is an invalid keyword argument for this function

第二:(带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是 []

一些细节:

a中对象的测试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()
4

2 回答 2

4

对于其他任何想要使用 Factory Boy 和 django-taggit 的更通用示例的人来说,Factory Boy 文档包含一个非常有用的多对多示例。所以:

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()

于 2017-04-06T11:25:56.630 回答
2

终于找到了解决方案:

@factory.post_generation
def post_tags(self, create, extracted, **kwargs):
    self.tags.add(u'abc, cde', u'xzy')
于 2014-11-11T17:30:41.887 回答