Create a mix of string and digit with Factory Boy in django
Asked Answered
V

2

5

I want to create a mix of string and digits like this: "XL1A" or "PP25" for one field in my database.How can I do that? I'm using only uppercase letter for now.

class CardFactory(DjangoModelFactory):
    class Meta:
        model = Card
    serial_number = FuzzyText(length=4, chars=string.ascii_uppercase)

Also, is there anyway to create random pattern rules for FuzzX in Factory Boy such as random IP addresses?

Vacuity answered 13/3, 2015 at 8:6 Comment(1)
Both solutions from catavaran and publysher work, so thank you both. I decided to go with catavaran's solution for my code because it's less coding. But the chosen solution is a generic way of generating random data with additional rules.Vacuity
B
5

You can create your own rules using the generic FuzzyAttribute. For example:

def generate_serial():
    return random.choice(string.ascii_uppercase) + random.choice(string.digits)

class CardFactory(DjangoModelFactory):
    class Meta:
        model = Card
    serial_number = FuzzyAttribute(generate_serial)

This will generate random serials like 'Q3'. Since the generate_serial function is just plain Python, you can make this is as complex as you want.

Bursitis answered 13/3, 2015 at 8:13 Comment(0)
S
6

Add the digits to the chars list?

serial_number = FuzzyText(length=4,
                          chars=string.ascii_uppercase + string.digits)
Spokesman answered 13/3, 2015 at 8:9 Comment(1)
very useful answer!Kodiak
B
5

You can create your own rules using the generic FuzzyAttribute. For example:

def generate_serial():
    return random.choice(string.ascii_uppercase) + random.choice(string.digits)

class CardFactory(DjangoModelFactory):
    class Meta:
        model = Card
    serial_number = FuzzyAttribute(generate_serial)

This will generate random serials like 'Q3'. Since the generate_serial function is just plain Python, you can make this is as complex as you want.

Bursitis answered 13/3, 2015 at 8:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.