tortoise / tortoise/tortoise-orm

update_or_create classmethod does not seem to work properly

Open
#885 5 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

When trying to invoke update_or_createclassmethod, it throws strange KeyError exception when updating ForeignKeyField

Model:

class Rating(BaseModel):
    value = fields.IntEnumField(Value,
                                description="Determines the rating's value",
                                null=False)
    left_by = fields.ForeignKeyField(model_name="models.User", related_name="left_ratings", null=False,
                                     on_delete=fields.CASCADE, description="User that left this rating")
    target_recipe = fields.ForeignKeyField(model_name="models.Recipe", related_name="ratings", null=False,
                                           on_delete=fields.CASCADE,
                                           description="Recipe for which this rating was issued")

Action:

 created_rating, _ = await Rating.update_or_create(
            defaults={"value": 3, "left_by_id": user_id, "target_recipe_id": recipe_id},
            left_by_id=user_id,
            target_recipe_id=recipe_id
        )

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 failure through the Rating model and the update_or_create entry point using the shown ForeignKeyField arguments. Trace how ForeignKeyField values are handled during the update path; done means the operation updates or creates the rating without raising KeyError.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.