tortoise / tortoise/tortoise-orm

Problems using `.raw()` instead of `.filter()`

Open
#1,667 1 comment 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
To get consistency between Tortoise-based and non-Tortoise based queries, I started replacing the usual <ModelClassName>.filter(...) fetches with <ModelClassName>.raw(<PlainSQLQueryString>).

It seemed to work, but I later found that saves were often not actually committing to the database. This caused some serious data consistency and workflow problems in several of my networks, which only came right after changing back to .filter(...).

Expected behavior
When using <ModelClassName>.raw(...) I was expecting the returned Model row objects to behave in the same way as the ones returned from awaiting a <ModelClassName>.filter(...) query.

Additional context
Is there a "safe" and recommended way to get Model row objects from raw SQL queries, which behave identically to those retrieved from .filter(...) ?

All help appreciated.

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 reported difference between ModelClassName.raw() and ModelClassName.filter(...) queries, focusing on whether returned model rows can be saved and committed. Review the raw-query and filter-query entry points and document a safe, consistent way to obtain model rows from raw SQL.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, sql
Domain
database
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.