Search code examples
djangofactory-boy

How to use factory.SelfAttribute with factory.Sequence?


I have model like so:

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

Now I am trying to build a factory:

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

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

The problem is, this does not work, while testing I get:

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

So how to use SelfAttribute with Sequence? I am using:

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

Solution

  • The problem was this was an incorrect way to do it. For sucha a task, that is creating sequences based on attributes I shoud've used LazyAttributeSequence. Like so:

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