ffigari
ffigari

Reputation: 451

One to One relationship in factory - Integrity Error

I'm using factory_boy to create the factories of the app I'm working on. I'm having an issue when trying to create the factory of a model which has a one to one relationship to another model.

Here are the models:

class Playlist(AccountDependantMixin, models.Model):
    test = models.OneToOneField('core.PlaylistTest', related_name='playlist')

class PlaylistTest(Test):
    pass

AccountDependantMixin is a class which contains extra information. It's outside because others models need it too. I have different kinds of test. That's why PlaylistTest is empty

This are the factories:

class PlaylistTestFactory(factory.DjangoModelFactory):
    class Meta:
        model = PlaylistTest


class PlaylistFactory(factory.DjangoModelFactory):
    class Meta:
        model = Playlist       
    test = factory.SubFactory(PlaylistTestFactory)

And here is how I'm trying to initialize the instance with the factory:

self.playlist = PlaylistFactory(creator=AdminUserFactory(account=self.account))

I'm getting the following error:

IntegrityError: null value in column "test_id" violates not-null constraint
DETAIL:  Failing row contains (1, , playlist0, sub_title0, description0, 0, t, f, 2016-03-31 12:49:23.739207+00, 0, 2, 1, null)

Upvotes: 1

Views: 1983

Answers (2)

ffigari
ffigari

Reputation: 451

The problem was I had another model with another one to one to another class that inherited from Test.

I added the subfactory to the factory of this other class and the problem was solved.

Upvotes: 0

Oin
Oin

Reputation: 7529

test = factory.RelatedFactory(PlaylistTestFactory)

You need to use a SubFactory rather than a RelatedFactory so that it creates the test object first:

A RelatedFactory behaves mostly like a SubFactory, with the main difference that the related Factory will be generated after the base Factory.

https://factoryboy.readthedocs.org/en/latest/reference.html#factory.RelatedFactory

Upvotes: 1

Related Questions