tortoise / tortoise/tortoise-orm

Typing issue with `ForeignKeyNullableRelation`

Open
#1,986 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

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?

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

Start by locating the definition of ForeignKeyNullableRelation and reproduce the mypy errors with the User and Ticket example in the issue. Trace the annotation used for the nullable relation and verify that assigning User or None to Ticket.solved_by type-checks without the reported errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.