tortoise / tortoise/tortoise-orm

Mixed model union queries behave like UNION ALL

Open
#2,185 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

Given the following models:

from tortoise import Model, fields

class Cat(Model):
    name = fields.CharField()

class Dog(Model):
    name = fields.CharField()

And the following rows:

await Cat.create(name='Charles')
await Dog.create(name='Charles')

Doing a select union on name will return two rows, as if all=True were specified:

cats = Cat.filter(name='Charles').only('name')
dogs = Dog.filter(name='Charles').only('name')
pets = await cats.union(dogs) # returns [Cat(name='Charles'), Dog(name='Charles')]

This happens because the model names are implicitly included in the SELECT query, which isn't obvious from the code alone. It also isn't entirely obvious what the code should do if it didn't do that (i.e., which model would it return for the one row).

I think supporting values()/values_list() for mixed model unions would make a lot of sense for the above case. Something like this:

cats = Cat.filter(name='Charles')
dogs = Dog.filter(name='Charles')
names = await cats.union(dogs).values('name') # returns ['Charles']

And maybe otherwise an error should be raised for mixed models if all=False and values() is not used?

Also, minor aside, but given the above example, the current implementation of union() also causes confusion with some type checkers such as basedpyright:

error: Argument of type "QuerySet[Dog]" cannot be assigned to parameter "other_qs" of type "QuerySet[Model]" in function "union"
    "QuerySet[Dog]" is not assignable to "QuerySet[Model]"
      Type parameter "MODEL@QuerySet" is invariant, but "Dog" is not the same as "Model" (reportArgumentType)

Maybe something like variadic generics could be used to fix this, but I'm not 100% sure.

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 with QuerySet.union and the values()/values_list() entry points, then inspect how mixed-model SELECT queries include model names. Determine the intended result and error behavior for mixed models with all=False, including the type-checking concern. Done means the requested values-based union behavior is covered by tests and the supported behavior is documented.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
database
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.