tortoise / tortoise-orm

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

Columns named `pk` cause RecursionError #1513

Open herbert-allium opened 7 months ago

herbert-allium commented 7 months ago
from tortoise import Tortoise, run_async, fields
from tortoise.models import Model

class TestModel(Model):
    pk = fields.IntField(pk=True)

async def main():
    await Tortoise.init(
        db_url="sqlite://memory", modules={"models": ["__main__"]}
    )
    await Tortoise.generate_schemas()
    await TestModel.create(pk=0)

run_async(main())

This errors with the following

Traceback (most recent call last):
  File "/Users/donjar/hack/good_tortoise.py", line 17, in <module>
    run_async(main())
  File "/Users/donjar/.pyenv/versions/3.9.14/lib/python3.9/site-packages/tortoise/__init__.py", line 688, in run_async
    loop.run_until_complete(coro)
  File "/Users/donjar/.pyenv/versions/3.9.14/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
    return future.result()
  File "/Users/donjar/hack/good_tortoise.py", line 14, in main
    await TestModel.create(pk=0)
  File "/Users/donjar/.pyenv/versions/3.9.14/lib/python3.9/site-packages/tortoise/models.py", line 1133, in create
    instance = cls(**kwargs)
  File "/Users/donjar/.pyenv/versions/3.9.14/lib/python3.9/site-packages/tortoise/models.py", line 672, in __init__
    for key in meta.fields.difference(self._set_kwargs(kwargs)):
  File "/Users/donjar/.pyenv/versions/3.9.14/lib/python3.9/site-packages/tortoise/models.py", line 699, in _set_kwargs
    setattr(self, key, field_object.to_python_value(value))
  File "/Users/donjar/.pyenv/versions/3.9.14/lib/python3.9/site-packages/tortoise/models.py", line 776, in _set_pk_val
    setattr(self, self._meta.pk_attr, value)
  File "/Users/donjar/.pyenv/versions/3.9.14/lib/python3.9/site-packages/tortoise/models.py", line 776, in _set_pk_val
    setattr(self, self._meta.pk_attr, value)
  File "/Users/donjar/.pyenv/versions/3.9.14/lib/python3.9/site-packages/tortoise/models.py", line 776, in _set_pk_val
    setattr(self, self._meta.pk_attr, value)
  [Previous line repeated 490 more times]
RecursionError: maximum recursion depth exceeded

Using other column names work, as is using this:

class TestModel(Model):
    pk2 = fields.IntField(pk=True, source_field="pk")
Prof1-web commented 7 months ago

Don't use this name =) It's python feature, you will always have reserved variables. For example, in pydantic you can't use a validator named "validator"