Closed li3807 closed 7 months ago
Looks fine to me, you must have a bug in your code. Please take time before opening issues.
from datetime import datetime
import uuid
from peewee import *
db = SqliteDatabase(':memory:')
class UserInfoModel(db.Model):
user_id = CharField(primary_key=True, null=False, max_length=64)
nickname = CharField(max_length=64)
profile_photo = CharField(null=True, max_length=255)
name = CharField(max_length=32)
status = IntegerField(default=0, null=False)
update_time = DateTimeField(null=False, default=datetime.now())
update_as = CharField(null=False, max_length=32, default="")
create_time = DateTimeField(null=False, default=datetime.now())
create_as = CharField(null=False, max_length=32, default="")
db.create_tables([UserInfoModel])
import logging
logger = logging.getLogger('peewee')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
user = UserInfoModel()
user.user_id = str(uuid.uuid4())
user.nickname = 'nick'
user.name = 'name'
user.update_as = '123'
user.create_as = '234'
user.save(force_insert=True)
print(user.user_id)
user_db = UserInfoModel.get(UserInfoModel.name == 'name')
print(user_db.user_id)
assert user.user_id == user_db.user_id
Example output:
('INSERT INTO "userinfomodel" ("user_id", "nickname", "name", "status", "update_time", "update_as", "create_time", "create_as") VALUES (?, ?, ?, ?, ?, ?, ?, ?)', ['1649e33a-8d67-4d57-9a89-f2e04ac2ca41', 'nick', 'name', 0, datetime.datetime(2024, 4, 2, 7, 47, 5, 921707), '123', datetime.datetime(2024, 4, 2, 7, 47, 5, 921717), '234'])
1649e33a-8d67-4d57-9a89-f2e04ac2ca41
('SELECT "t1"."user_id", "t1"."nickname", "t1"."profile_photo", "t1"."name", "t1"."status", "t1"."update_time", "t1"."update_as", "t1"."create_time", "t1"."create_as" FROM "userinfomodel" AS "t1" WHERE ("t1"."name" = ?) LIMIT ? OFFSET ?', ['name', 1, 0])
1649e33a-8d67-4d57-9a89-f2e04ac2ca41
The assertion succeeds.
I created the BaseModel class to handle the problem of database selection, using the Mysql database。
··· def save(self, force_insert=False, only=None):
field_dict = self.__data__.copy()
···
Model code(模型代码):
Test code(测试代码):
Execution log(执行日志):
As you can see from the log, the insert statement does not include the user_id primary key. Check the source code: 可以看到日志,insert 语句没有包括 user_id 主键,查看源码: