Skip to content

Typing issue with ForeignKeyNullableRelation #1986

@Pirulax

Description

@Pirulax

Describe the bug
Using mypy I get typing errors:

Incompatible types in assignment (expression has type "User | None", variable has type "ForeignKeyFieldInstance[Any] | None")
Cannot assign to attribute "solved_by" for class "Ticket"
  Type "User | None" is not assignable to type "ForeignKeyNullableRelation[User]"
    Type "User" is not assignable to type "ForeignKeyNullableRelation[User]"
      "User" is not assignable to "ForeignKeyFieldInstance[User]"
      "User" is not assignable to "None"
(parameter) solved_by: User | None

To Reproduce
I have (pretty much) the following code:

from tortoise.models import Model

class User(Model):
    id = fields.IntField(unique=True, pk=True)

class Ticket(Model):
    id = fields.IntField(unique=True, pk=True)

    solved_by : fields.ForeignKeyNullableRelation[User] = fields.ForeignKeyField("User", "solved_tickets", null=True)

And the following is causing the issue:

async def set_solved_by(self, solved_by: User | None): # self here is a wrapper class with a state, `model` is an instance of `Ticket`
    self.model.solved_by = solved_by 

Expected behavior
To not get typing errors

Additional context
I'm not quite sure if I'm using the correct typing for the field, but I assume I do?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions