python-gino / gino

GINO Is Not ORM - a Python asyncio ORM on SQLAlchemy core.
https://python-gino.org/
Other
2.68k stars 150 forks source link

Subclass overrides the parent method(update/delete) problem #709

Closed ferstar closed 4 years ago

ferstar commented 4 years ago

Description

I wrote a Model class and overridden the update/delete method, but found that it didn't work at all. The code example is as follows:

import asyncio
db = Gino()

class BaseModel(db.Model):
    id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
    created_utc = db.Column(db.Integer, default=int(time.time()))
    updated_utc = db.Column(db.Integer, default=int(time.time()))

    async def update(self, **kwargs):
        kwargs.setdefault('updated_utc', int(time.time()))
        await super().update(**kwargs).apply()

    async def delete(self):
        if 'deleted_utc' in self.columns():
            await self.update(deleted_utc=int(time.time()))
        else:
            await super().delete()

class User(BaseModel):
    __tablename__ = 'users'
    name = db.Column(db.String, default='noname')

async def main(loop):
    async with db.with_bind(loop=loop):
        await db.gino.create_all()
        user = User(name='fantix niubility')
        await user.create()
        user = await User.get(1)
        await user.update(name='help me!')  # It should update user name here but actually didn't
        await user.delete()
        print(user.to_dict())

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))

What I Did

I don't understand what is wrong with inheritance here. The traceback info is as follows:

...
  File "~/.pyenv/versions/mypyenv/lib/python3.6/site-packages/gino/crud.py", line 162, in apply
    type(self._instance)
AttributeError: 'function' object has no attribute 'where'

https://github.com/python-gino/gino/blob/master/src/gino/crud.py#L162

wwwjfy commented 4 years ago

As you see, it's not a function https://github.com/python-gino/gino/blob/7781848cf035e8a2afedc53d653e48c112c80e90/src/gino/crud.py#L329 The behavior is different for Model.update and instance.update

ferstar commented 4 years ago

@wwwjfy yeah, I'd noticed that, thx.