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

Can't use check field name #1559

Closed Arteemoon closed 1 month ago

Arteemoon commented 4 months ago
from enum import Enum
from tortoise import models, fields

from models.users import User

class PaymentTypeEnum(Enum):
    CASH = 'cash'
    CASHLESS = 'cashless'

class Check(models.Model):
    id = fields.IntField(pk=True)
    created_by: fields.ForeignKeyRelation[User] = fields.ForeignKeyField('models.User', null=False)
    payment_type = fields.CharEnumField(enum_type=PaymentTypeEnum)
    payment_amount = fields.DecimalField(max_digits=8, decimal_places=2)
    created_at = fields.DatetimeField(auto_now_add=True)

class Product(models.Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=30)
    price = fields.DecimalField(max_digits=8, decimal_places=2)
    quantity = fields.IntField()
    check: fields.ForeignKeyRelation[Check] = fields.ForeignKeyField(Check, null=False, related_name='products')

this is my code, when i try run aerich migrate

Get this error

File "/usr/local/lib/python3.10/site-packages/tortoise/backends/base/schema_generator.py", line 185, in _get_table_sql self._get_models_to_create(models_to_create) File "/usr/local/lib/python3.10/site-packages/tortoise/backends/base/schema_generator.py", line 412, in _get_models_to_create model.check() TypeError: 'property' object is not callable

lucasbrahm commented 4 months ago

CharEnumField expects an instance of type str, so you could modify your enum to:

class PaymentTypeEnum(str, Enum): CASH = 'cash' CASHLESS = 'cashless' Check some example here: https://tortoise.github.io/examples/basic.html?h=charenumfield#enumeration-fields

vlakius commented 2 months ago

what @lucasbrahm said is true but i think that the problem here is a name collision with the field "check" that collide with the method "check" of the models. If i'm right it could be a good idea to rename the internal methods with something like _check to avoid name collision EDIT: this is the classmethod causing the problem: https://github.com/tortoise/tortoise-orm/blob/5c8d81c554f210a191a36f373c6a66a2d9943412/tortoise/models.py#L1369C1-L1375C42

abondar commented 2 months ago

Yeah, check being reserved seems like bad decision :) I'll look into renaming it

abondar commented 1 month ago

In 0.21.0 you should be able to use check field name