tortoise / tortoise-orm

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

source_field break __iter__ #1115

Open enneamer opened 2 years ago

enneamer commented 2 years ago

Describe the bug When a field specifies source_field, Model.__iter__() no longer works.

To Reproduce

from tortoise import Model
from tortoise.fields import BigIntField
class SampleModel(Model):
    id_ = BigIntField(pk=True, source_field='id')

a = SampleModel(id_=1)
[i for i in a]

Expected behavior This iteration sho

Additional context Python 3.10.4 tortoise-orm==0.19.0

enneamer commented 2 years ago

I can see in the source code models.py:761

    def __iter__(self):
        for field in self._meta.db_fields:
            yield field, getattr(self, field)

It iterates over the database fields instead of the object fields, but also tries to fetch the object attribute value instead.

enneamer commented 2 years ago

I happen to have use cases for iterating over object fields (for manual dataclass mapping) and database fields (for database debugging). I wonder what is the original intention of this function, and what is the correct way for the other use case.