pytest-dev / pytest-dev/pytest-factoryboy

Subfactory does not work with self-referencing ForeignKey relationships

Open
#94 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
400
Forks
44
Avg merge
6h 34m
Merged PRs (30d)
1

Description

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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the registered MyAuthorFactory and the SubFactory('app.factories.MyAuthorFactory') entry point, then trace how the pytest fixture named myauthor is built. Done means a self-referencing ForeignKey factory no longer triggers the reported recursive dependency error.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
database, testing
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.