如何从 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()