Skip to content

Database access not allowed when passing function to default foreign key #923

Open
@buddylindsey

Description

@buddylindsey

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions