Repository navigation
Description
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
ormarversion: upstream HEAD (67d8106); the template links point to collerek/ormar, the repo is now ormar-orm/ormarpydanticversion: 2.13.5- if applicable
fastapiversion: 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:
ormar/ormar/queryset/queryset.py
Lines 1197 to 1213 in 67d8106
| 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
fix: check exclude clauses before the unfiltered get() shortcut (orma…