pytest-dev / pytest-dev/pytest-django
`Database access not allowed` when passing function to default foreign key
Nobody has claimed this yet.
- 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
)
- This works with django since default is either looking for a value or a callable.
- It works in migrations since it is being called after all of the apps are initialized.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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