tortoise / tortoise/tortoise-orm

TypeError: error: Incompatible types in assignment (expression has type "Clan", variable has type "Optional[ForeignKeyFieldInstance[Clan]]")

Open
#1,314 0 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
Getting a type error when updating the ForeignKey field to a different clan on a Nullable Foreign Key Field instance.

To Reproduce

if await Clan.get_or_none(tag=clantag):
	clan = await Clan.get(tag=clantag)
	if await Player.get_or_none(name=playername):
		if await Season.active_seasons.all().exists():
			await ctx.send("Cannot move players between clans during an active season.")
		else:
			player = await Player.get(name=playername)
			if player.is_enabled():
				player.clan = clan
				await player.save()
				await ctx.send(
					f"Welcome @{playername} to the [{clan.tag}] {clan.name} Clan roster!"
				)
			else:
				player.clan = clan
				await player.save()
				await ctx.send(
					f"Welcome @{playername} to the [{clan.tag}] {clan.name} Clan roster!"
				)
	else:
		await Player.create(name=playername, clan=clan, enabled=True)
		await ctx.send(
			f"Welcome @{playername} to the [{clan.tag}] {clan.name} Clan roster!"
		)
else:
	await ctx.send(f"Clan {clantag} does not exist.")

Expected behavior
This shouldn't error as the code works fine and foreign key field gets updated fine.

Additional context
Add any other context about the problem here.

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 reproducing the nullable ForeignKey assignment shown in the issue, focusing on assigning a Clan instance to player.clan and then saving the Player. Trace the model and type definitions involved in that field, and verify that static checking accepts the assignment while saving still updates the relation correctly.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.