Skip to content

Derived ForeignKey field type "is nullable but its generic get type parameter is not optional" #2403

Closed
@tik-stbuehler

Description

@tik-stbuehler

Hi.

I'm getting is nullable but its generic get type parameter is not optional for fields with derived ForeignKey field types.

Given my main model uses a "name" as primary key, I'd like to use _name instead of _id as attname and dbcolum suffix, and I think I can only overwrite dbcolumn in a fields constructor (not the attname).

Demo code:

class ForeignNameKey(models.ForeignKey):
    def get_attname(self) -> str:
        return '%s_name' % self.name


class Domain(models.Model):
    name = models.CharField(unique=True, max_length=255, blank=False, primary_key=True)


class Foo(models.Model):
    domain = ForeignNameKey(
        Domain,
        on_delete=models.RESTRICT,
        null=True,
    )

-> error: ForeignNameKey is nullable but its generic get type parameter is not optional

I tried understanding what the code from #2048 does, but couldn't figure out why it works with models.ForeignKey and not with my derived class. Also the error message is completely useless - I have no idea how to "fix" it (also unclear what is wrong; I don't think anything is actually wrong).

System information

  • OS: debian bookworm
  • python version: 3.11.2
  • django version: 5.1.2
  • mypy version: 1.11.2
  • django-stubs version: 5.1.0
  • django-stubs-ext version: 5.1.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions