jeudi 31 mars 2016

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):
    image = models.ImageField(_('image'), upload_to='playlist/images/', blank=True, null=True)

    title = models.CharField(_('title'), max_length=100)
    sub_title = models.CharField(_('sub_title'), max_length=100)
    description = models.TextField(_('sub_title'), max_length=1000, blank=True, null=True)

    _ranking = models.IntegerField(_('ranking'), default=0)
    creator = models.ForeignKey('core.User', related_name="playlists")
    categories = models.ManyToManyField('core.Category', related_name="playlists", blank=True)

    is_published = models.BooleanField(_('published'), default=False)
    is_shared = models.BooleanField(_('shared'), default=False)

    visible_for = models.ManyToManyField('core.Group', related_name="visible_playlists")
    mandatory_for = models.ManyToManyField('core.Group', related_name="mandatory_playlists")

    test = models.OneToOneField('core.PlaylistTest', related_name='playlist')

    created_on = models.DateTimeField(auto_now_add=True)

    amount_of_views = models.IntegerField(blank=True, default=0)

class PlaylistTest(Test):
    pass

This are the factories:

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


class PlaylistFactory(factory.DjangoModelFactory):
    class Meta:
        model = Playlist
    title = factory.Sequence(lambda n: 'playlist%d' % n)
    creator = factory.SubFactory(InstructorUserFactory)
    sub_title = factory.Sequence(lambda n: 'sub_title%d' % n)
    description = factory.Sequence(lambda n: 'description%d' % n)
    test = factory.RelatedFactory(PlaylistTestFactory)
    is_published = True

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).

I have not found much documentation about one to one relationships and factory boy, and what I have found has not been useful to solve the problem. I thought it could be because the PlaylistTest model was empty, but I added some fields to it and the problem persisted.

Aucun commentaire:

Enregistrer un commentaire