tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.37k stars 355 forks source link

OperationalError when attempting to filter by annotated field in m2m relation #1616

Open aquarell-dev opened 1 month ago

aquarell-dev commented 1 month ago

The problem So, basically, i'm trying to filter a m2m related field, the m2m related field has profit and volume. I created annotations for max_volume and max_profit, and also i wanna filter by the annotated field to exclude those rows where max_profit or max_volume is null, but i get the "column doesn't exist" error, which is clearly false. Moreover, i've run the raw query on the database itself and it worked.

arbitrages = Arbitrage.all().annotate(
        max_profit=Max(
            "offers__profit",
            _filter=Q(offers__profit__gt=profit)
        )
    ).annotate(
        max_volume=Max(
            "offers__volume",
            _filter=Q(offers__volume__lt=volume + 1)
        )
    ).filter(max_volume__isnull=False).prefetch_related(
        "buy",
        "sell",
        "network",
        Prefetch("offers", queryset=Offer.filter(Q(volume__lt=volume + 1) & Q(profit__gt=profit)))
    ).order_by("-max_volume", "-max_profit")

this method .filter(max_volume__isnull=False) basically triggers the error

Expected behavior I'm a bit confused here, it should just perform the filtering, but somehow it just won't. Moreover, due to a lack of exeperience with Tortoise i can't even write my own query and convert it to QuerySet, well, i can, but it ain't gonna look pretty.

abondar commented 1 month ago

Hello!

Please provide minimal reproducible code snippet, so that I could reproduce it locally