pytest-dev / pytest-dev/pytest-django

`Database access not allowed` when passing function to default foreign key

Open
#923 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

needs-info
Dominant language
Python
Stars
1.5k
Forks
367
PR merge metrics
No merged PRs in 30d

Description

I am getting the following error when I am setting a function as a default value for a foreign key. I have the decorator on many tests, but it doesn't even finish loading the first test with the decorator before exploding.

Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

Here is what I have:

class Score(models.Model):
    def default_value():
        return Sport.objects.get(game='football').id

    sport = models.ForeignKey(
        Sport,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        default=default_value
    )
  1. This works with django since default is either looking for a value or a callable.
  2. It works in migrations since it is being called after all of the apps are initialized.
  3. It also just works in the normal course of using the project

I suspect this is just tripping up the order of something getting loaded.

Contributor guide

Open the contributing guide

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

Reproduce the failure with the shown Score model and the first test using the database decorator. Trace pytest-django’s database-access setup and Django app initialization order to identify why the callable default is evaluated before database access is enabled. Done means the example loads without the error while existing database-access protections remain intact.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
testing
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.