我无法初始化peewee模型“使用通常的init()方法的子代对象。我怎样才能交替初始化?在
import peewee
peewee_database = peewee.SqliteDatabase('example.db')
class Config():
def __init__(self, seats, cylinders):
self.seats = seats
self.cylinders = cylinders
class Car(peewee.Model):
magic_number = peewee.IntegerField()
color = peewee.TextField()
class Meta:
database = peewee_database
def __init__(self, config):
self.magic_number = config.seats / config.cylinders
self.color = None
peewee_database.connect()
peewee_database.create_tables([Car])
config = Config(7, 6)
car = Car(config)
car.color = "blue"
car.save()
在Python3中生成以下错误:
^{pr2}$救命啊!:)
这位小人物的作者很好地回答了自己的问题。我认为使用factory方法是最干净的解决方案,以避免与peewee使用yu init()的方式冲突
你做的有点不对。 你可以把pewee用来数据库管理的类Car分离出来,用其他类比如“class ACar():”来创建你的对象Car,然后你可以调用Car.get_或_create(魔术号码=汽车魔术号码,颜色=汽车颜色). 请参阅有关创建记录的peewee文档。因为你使用的方式是错误的。 你保存的是车,是车的对象,而不是peewee在使用后想还给你的模块车。去还是不去(...). 即使您将使用save,也需要在数据库中已经存在的记录中使用它。如果要创建新记录,请使用create(),它是一个类方法(意思是,汽车.创建()). 希望这能给你和如何重写代码的想法。 即使你想要一辆车,也要用汽车.创建(…)要创建记录而不是对象,如果已经有记录,对象car=car()这是不对的,正确的方法是car=车。去还是不去(“你的参数”)。 Car.get_或_create(…)将创建不存在的记录,请参阅文档
相关问题 更多 >
编程相关推荐