Search code examples
mysqlpython-3.8fastapipeewee

Error creating tables in MySQL using peewee and FastAPI


I have below basic code where I am trying to create tables in food_delivery database using peewee ORM. I am receiving error as below:

AttributeError: 'str' object has no attribute 'safe_create_index'

My Code below:

DATABASE = 'food_delivery'
db = MySQLDatabase(
    host='localhost',
    user='my_user',
    password='****',
    database=DATABASE
)

class BaseModel(Model):
    class Meta:
        database = DATABASE

class Customer(BaseModel):
    city = CharField()
    customer = AutoField(column_name='customer_id')
    email = CharField(column_name='email_id',unique=True)
    first_name = CharField()
    landmark = CharField()
    last_name = CharField()
    password = CharField()
    phone_no = CharField(max_length=10)
    pincode = IntegerField()
    state = CharField()

    class Meta:
        table_name = 'customer'
        database = DATABASE
def create_tables():
    with db:
        db.create_tables([Customer])
create_tables()

Can someone suggest what might be wrong with code? Thanks!


Solution

  • I kept looking for issue and found that I had a logical syntax misplacement basically. Instead of database name under all the table definition in META, I actually had to pass connection instance of database instead of database name. But I wonder how inappropriate the thrown error is and its kind of impossible to fi seeing the error details. This requires much improvement by library maintainers.