Django Integrity Error:Cannot add or update a child row: a foreign key constraint fails using factory_boy in django unit test

Viewed 556

I started writing unit tests for my django app, and I used factory boy to create objects with data. but I'm having this error

IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails

This my code :

models.py

class Group(models.Model):
    created_by = models.ForeignKey(User)
    name = models.CharField(_('Name'), max_length=100)
    description = models.TextField(_('Description'), max_length=1000)
    members = models.ManyToManyField(User, verbose_name='Members', 
    related_name='member', blank=True)


class User(models.Model):
    username = models.CharField(_('username'),max_length=30,unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    password = models.CharField(_('password'), max_length=128)

factories.py

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
       model = models.User
    # to have unique user names
    username = factory.Sequence(lambda n: 'name%d' % n)
    first_name = factory.Faker('first_name')
    last_name = factory.Faker('last_name')
    # email based on the username
    email = factory.LazyAttribute(lambda obj: '%s@example.com' % obj.username)
    password = 'admin'


class GroupFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Group

    created_by = factory.SubFactory(UserFactory)

    @factory.post_generation
    def members(self, create, extracted, **kwargs):
        if not create:
            # GroupFactory.build()
            return

        if extracted:
            # A list of users were passed in, use them
            for member in extracted:
                self.members.add(member)

and in tests.py I wanted to test the Group model, here how I'm creating Group instance:

class GroupTest(BaseModelTest):
    model = Group
    group = GroupFactory.build()

BaseModelTest contains some abstract methods to test edit , add models ..etc ..

I think with factory boy when declaring user as a sub factory it should be created before creating the Group instance .. why I have this error : IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (``test_db_``.``members_group``, CONSTRAINT ``members_group_created_by_id_2f561a30_fk_members_user_id`` FOREIGN K EY (``created_by_id``) REFERENCES ``members_user`` (``id``))') ?

0 Answers
Related