1

我有这样的模型:

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 与 Sequence 结合使用呢?我在用:

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

1 回答 1

2

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

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

    category = FuzzyChoice(['gadżety', 'jedzenie'])
    name = LazyAttributeSequence(lambda o,n: "%s%d" % (o.category, n))
于 2016-09-09T11:03:35.313 回答