Skip to content

QuerySet.get() after exclude() returns an arbitrary row instead of raising MultipleMatches #1858

Closed

Description

@moneebullah25

Describe the bug
QuerySet.get() (ormar/queryset/queryset.py:1197-1213) takes the "no criteria" fast path (LIMIT 1, ordered by pk descending) when not self.filter_clauses. exclude() fills exclude_clauses, not filter_clauses, so a queryset with only excludes is treated as unfiltered: the limit hides the other matches and MultipleMatches is never raised. update() and delete() in the same file already check both clause lists (lines 913 and 953). get_or_none() and any uniqueness check built on exclude() inherit this.

To Reproduce

import asyncio

import ormar
import sqlalchemy
from ormar.exceptions import MultipleMatches

database = ormar.DatabaseConnection("sqlite+aiosqlite:///test.db")
metadata = sqlalchemy.MetaData()
cfg = ormar.OrmarConfig(database=database, metadata=metadata)


class Cat(ormar.Model):
    ormar_config = cfg.copy(tablename="cats")

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=50)


async def main():
    async with database:
        engine = sqlalchemy.create_engine("sqlite:///test.db")
        metadata.drop_all(engine)
        metadata.create_all(engine)
        for n in "abc":
            await Cat.objects.create(name=n)

        cat = await Cat.objects.exclude(name="zzz").get()
        print(f"get-after-exclude name={cat.name!r}")

        try:
            await Cat.objects.filter(name__in=["a", "b", "c"]).get()
        except MultipleMatches:
            print("filter(...).get(): MultipleMatches")


asyncio.run(main())

Output:

get-after-exclude name='c'
filter(...).get(): MultipleMatches

Cat.objects.filter(name__in=['a','b','c']).get() raises MultipleMatches for the same three rows, while exclude(name="zzz").get() matches all three and silently returns the last one.

Expected behavior
MultipleMatches is raised, as for filter(...).get() matching several rows.

Screenshots
Not applicable.

Versions (please complete the following information):

  • Database backend used (mysql/sqlite/postgress): sqlite (aiosqlite)
  • Python version: 3.14.0
  • ormar version: upstream HEAD (67d8106); the template links point to collerek/ormar, the repo is now ormar-orm/ormar
  • pydantic version: 2.13.5
  • if applicable fastapi version: not used

Additional context
A possible fix is if not (self.filter_clauses or self.exclude_clauses):, matching update() and delete(), plus a test: three rows, exclude(name="zzz").get() raises MultipleMatches, and exclude(name="a").get() with one remaining row still works.

Code reference:

if not self.filter_clauses:
expr = self.build_select_expression(
limit=1,
order_bys=(
[
OrderAction(
order_str=f"-{self.model.ormar_config.pkname}",
model_cls=self.model_cls, # type: ignore
)
]
if not any([x.is_source_model_order for x in self.order_bys])
else []
)
+ self.order_bys,
)
else:
expr = self.build_select_expression()

Activity

  1. added a commit that references this issue on Oct 19, 2026
    f3d4a62
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions