tortoise / tortoise/tortoise-orm

Fix for #443 Generates incorrect queries

Open
#822 3 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
From my testing the fix for #443 does not work quite correctly when updating the model. Although the original error is solved it would seem when doing an update query on the model the _id is not appended to the primary key correctly. I assume because no other primary keys need to do this.

To Reproduce

class Order(models.Model):
    id = fields.UUIDField(pk=True, default=uuid.uuid4)

class OrderCustomerDetails(models.Model):
    order: fields.OneToOneRelation[Order] = fields.OneToOneField(
        "models.Order", on_delete=fields.CASCADE, related_name="customer_details", pk=True
    )

Using models similar to above if I was to runt he following code

details = await OrderCustomerDetails.get(order=order)
# Edit some value
await details.save()

The query used would be similar to below:

UPDATE "order_customer_info" SET "name"=$1 WHERE "order"=$2

Expected behavior
I believe there needs to be logic to check if its a relation and add on _id when doing the where for an update query so it's like below.

UPDATE "order_customer_info" SET "name"=$1 WHERE "order_id"=$2

I did try and see if I could fix this myself but got lost in the code.

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 issue with the Order and OrderCustomerDetails models shown, then follow the query generation reached by details.save(). Compare the generated UPDATE condition with the expected order_id column. Done means updates through the relation-backed primary key generate the correct WHERE clause.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, sql
Domain
databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.