tortoise / tortoise/tortoise-orm
Not possible temporary set None to non nullable fields using Model(**dict)
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
It is not possible to temporary set None to non nullable fields using Model(**dict)
To Reproduce
from typing import Optional, List
from tortoise import Tortoise, run_async, Model, fields, BaseDBAsyncClient
class FootballTeam(Model):
id = fields.IntField(pk=True)
name = fields.TextField()
members_count = fields.IntField(null=False)
created_at = fields.DatetimeField(auto_now_add=True)
class Meta:
ordering = ["name"]
async def save(self, using_db: Optional[BaseDBAsyncClient] = None,
update_fields: Optional[List[str]] = None) -> None:
if not self.members_count:
self.members_count = 11
return await super().save(using_db, update_fields)
async def run():
await Tortoise.init(db_url="sqlite://db.sqlite3", modules={"models": ["__main__"]})
await Tortoise.generate_schemas()
team = FootballTeam()
team.name = "test"
await team.save()
data = {"name": "test2"}
team2 = FootballTeam(**data)
await team2.save()
data = {"name": "test3", "members_count": None}
filtered_data = {}
for key, value in data.items():
if value is not None:
filtered_data.update({key: value})
team3 = FootballTeam(**filtered_data)
await team3.save()
data = {"name": "test4"}
team4 = FootballTeam(**data)
team4.members_count = None # << no problem
await team4.save()
data = {"name": "test5", "members_count": None} # << problem
team5 = FootballTeam(**data) # << ValueError: members_count is non nullable field, but null was passed
await team5.save()
if __name__ == "__main__":
run_async(run())
Expected behavior
It must work as in example with team4.
Seems best way to fix this is just set continue in line 654 of tortoise-orm model.py instead of raising ValueError Exception.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the behavior with the provided FootballTeam example, then inspect tortoise-orm/model.py around line 654 where the non-nullable-field error is raised. Confirm the constructor accepts None for this case while preserving the expected save behavior, and verify the example completes without the ValueError.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python, sqlite
- Domain
- backend, databases
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100