tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

source_field break __iter__

Open enneamer opened this issue 3 years ago • 2 comments

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 avatar Apr 28 '22 15:04 enneamer

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 avatar Apr 28 '22 15:04 enneamer

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.

enneamer avatar Apr 28 '22 16:04 enneamer