如何使用factory.SelfAttribute with factory.Sequence?

时间:2016-09-09 10:55:54

标签: django factory-boy

我有这样的模型:

class ItemGroup(models.Model):
    group_id = models.AutoField(primary_key=True)
    category = models.CharField(max_length=200, blank=True, null=True)
    name = models.CharField(max_length=45, blank=True, null=True)

    def __str__(self):
        return self.name

现在我正在尝试建立一个工厂:

class ItemGroupFactory(DjangoModelFactory):
    class Meta:
        model = ItemGroup

    category = FuzzyChoice(['category1', 'category2'])
    name = Sequence(lambda n: "%s%d" % (SelfAttribute("category"), n))

问题是,这不起作用,而测试我得到:

django.db.utils.DatabaseError: Data too long for column 'name' at row 1

那么如何在序列中使用SelfAttribute? 我正在使用:

Django  1.8.14
djangorestframework 3.4.6
fake-factory    0.5.3   
mysql-connector-python  2.1.3
factory-boy 2.7.0   

1 个答案:

答案 0 :(得分:1)

问题是这是一种不正确的方法。对于一项任务,即根据我已经使用LazyAttributeSequence的属性创建序列。像这样:

class ItemGroupFactory(DjangoModelFactory):
    class Meta:
        model = ItemGroup

    category = FuzzyChoice(['gadżety', 'jedzenie'])
    name = LazyAttributeSequence(lambda o,n: "%s%d" % (o.category, n))