I have a Model Sector which has a id field (pk) which is UUID4 type. I am trying to populate that table(Sector Model) using faker and factory_boy.
But,
JavaScript
x
2
1
DETAIL: Key (id)=(46f0cf58-7e63-4d0b-9dff-e157261562d2) already exists.
2
This is the error I am getting.
Is it possible that the error is due to the fact that everytime I am creating SectorFactory objects (which is in a different django app) and the seed gets reset to some previous number causing the uuid to repeat?
Please suggest some ways as to how I shall get unique uuid for each Factory object?
SectorFactory class
JavaScript
1
14
14
1
import uuid
2
from factory.django import DjangoModelFactory
3
from factory.faker import Faker
4
from factory import Sequence
5
6
7
class SectorFactory(DjangoModelFactory):
8
id = uuid.uuid4()
9
name = Sequence(lambda n: f'Sector-{n}')
10
11
class Meta:
12
model = 'user.Sector'
13
django_get_or_create = ['name']
14
Class Sector
JavaScript
1
10
10
1
class Sector(models.Model):
2
id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False)
3
name = models.CharField(max_length=100)
4
5
class Meta:
6
db_table = 'sector'
7
constraints = [
8
models.UniqueConstraint('name', name = 'unique_sector_name')
9
]
10
The script which creates the custom command to create SectorFactory objects.
JavaScript
1
23
23
1
from types import NoneType
2
from django.core.management.base import BaseCommand
3
from user.factories import SectorFactory
4
5
class Command(BaseCommand):
6
help = 'Generate fake data and seed the models with them.'
7
8
9
def add_arguments(self, parser) -> None:
10
parser.add_argument( '--amount', type=int, help='The amount of fake objects to create.' )
11
12
def _generate_sectors(self, amount):
13
for _ in range(amount):
14
SectorFactory()
15
16
def handle(self, *args, **options) :
17
18
amount = options['amount']
19
if(type(amount) == NoneType): amount = 10
20
21
self._generate_sectors(amount)
22
23
Advertisement
Answer
just use like this:
JavaScript
1
8
1
class SectorFactory(DjangoModelFactory):
2
id = Faker('uuid4')
3
name = Sequence(lambda n: f'Sector-{n}')
4
5
class Meta:
6
model = 'user.Sector'
7
django_get_or_create = ['name']
8