tortoise / tortoise-orm

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

model relationship bugged #1572

Closed xalteropsx closed 2 months ago

xalteropsx commented 3 months ago

data come in unknown format after sometime the relationship itself break

msgx: fields.ManyToManyRelation["Messagex"] = fields.ManyToManyField("tortmodels.Messagex", related_name="personxs", through="personx_messagex")

    data = await Personx.get(id=id).prefetch_related("msgx")
    async for dx in data.msgx:
          print(dx.id)

image

xalteropsx commented 3 months ago

@long2ice why 161 come earlier many time the relationship itself break to bring correct format // mostly it occur on more then 160 above entry of data

xalteropsx commented 3 months ago

image here the evidence of ur prefetch_related break if u need further evidence i can create a reproduction of this issue

YAGregor commented 3 months ago

why don't u specialize the ordering? like

 data = await Personx.get(id=id).prefetch_related(Prefetch("msgx", queryset=Msg.all().order_by("id")))

and why do you consider it as a bug of tortoise? have you executed the raw sql that tortiose generated, and checked the ordering that the database direct return?

ref: https://tortoise.github.io/query.html#complex-prefetch

xalteropsx commented 3 months ago

havent thought about raw retrieveal for this part but i guess i will check it soon bro >,</ but isnt the data always come in an ascending manner ? // thanks ^_^/ i didnt aware we can order prefetch like that

YAGregor commented 3 months ago

but isnt the data always come in an ascending manner ?

I think that it depends on which database you use.You may set a default ordering of a model, but what is the ordering if you don't change anything? At least it does not guarantee any ordering explicitly.

xalteropsx commented 3 months ago

ah i didnt aware but i using the postgresql i think i will use python postgresql plugin to check raw data soon but i think u right

xalteropsx commented 3 months ago

between is it possible to get it on reverse order base on id i tried many time but i dont know what i missing

data = await Personx.get_or_none(id=id).prefetch_related(Prefetch("msgx", queryset=Messagex.all().order_by("-id")))
async for dx in data.msgx:
     print(dx.id)

image

abondar commented 2 months ago

Default return order is not guaranteed in most databases and it is out of scope of tortoise to tweak it Please use order_by if you rely on ordering