pytest-factoryboy icon indicating copy to clipboard operation
pytest-factoryboy copied to clipboard

Subfactory does not work with self-referencing ForeignKey relationships

Open biletboh opened this issue 4 years ago • 1 comments

It seems to be that SubFactory does not work with self-referencing ForeignKey relationships. I have a model with a foreign key to self:

class MyAuthor(Model):
    full_name = CharField('Full name', max_length=255)
    original_author = ForeignKey('self', null=True)

This is the factory I tried to use:

class MyAuthorFactory(factory.django.DjangoModelFactory):
    full_name = 'John Doe'
    original_author = factory.SubFactory('app.factories.MyAuthorFactory')

    class Meta:
        model = 'app.models.Author'

I registered the factory like this:

register(MyAuthorFactory, 'myauthor')

And got this error:

recursive dependency involving fixture 'myauthor' detected
available fixtures: ... myauthor, myauthor__full_name, ...

biletboh avatar Aug 24 '20 16:08 biletboh

True. Try using a related_name in the model and the following in the factory: factory.RelatedFactory('app.factories.MyAuthorFactory', factory_related_name='parent')

MRigal avatar Jun 23 '21 14:06 MRigal