Quick Post – Django Factory Boy

I’ve been using factoryboy in my tests as of late. It’s a nice tool to create test data in a programmatic way – no fixtures.

A factory includes a Sequence class that can be used to create unique field values with each instance. The examples I’ve seen use something like this:

title = factory.Sequence(lambda n: 'Event ' + n)

Which will create successive records with titles like “Event 0”, “Event 1″, Event 2”, etc.

The variable n is a string type by default, but I wanted to use it as an integer – in this case to set a value to an Integer field:

capacity = factory.Sequence(lambda n: n * 10)

However, this instead put 10 ones in the field, instead of the number held in n times 10.

A quick perusing of the documentation here showed that the Sequence class takes a second parameter after the function that indicates the desired type for n. Adding int to the end of the call makes it work much better.

capacity = factory.Sequence(lambda n: n * 10,int)

Now the field holds a multiple of 10.

Want a more complicated example? Here I assign a date field that is n nubmer of days after the current date.

event_date = factory.Sequence(lambda n:(datetime.now() + timedelta(days=n)).date(), int)