Peewee:使用 CompositeKey 的模型中出现 create_or_get() 错误
Peewee: create_or_get() error in Model with CompositeKey
我有这样一个模型:
class ProductOrderItem(BaseModel):
prodorder = peewee.ForeignKeyField(modprodord.ProductOrder, related_name='items')
cid = peewee.IntegerField(null=False)
class Meta:
db_table = 'TBWOHPARGDET'
primary_key = CompositeKey('prodorder','cid')
这样做的目的是用这样的东西构建一个 table:
|ID_ORDER|ID_ORDERLINE|
| 1| 1|
| 1| 2|
| 1| 3|
| 2| 1|
Appart,在我的BO层,我想判断这个对象之前是否创建过。所以我使用 create_or_get(method)
只是为了接收 created 变量或对应于提供的 PK 字段的 lineOrder - 我的意思是,通过方法在数据库中找到的对象 - :
for idx,x in enumerate(collection):
lineOrder, created = ProductOrderItem.create_or_get(order=orderObj,orderline=idx,[rest_of_fields])
if(created): # this is when the object was created
else: # this is when the object with those PK's was found in database
# this is where I want to add the rest of fields, in other this linea I have the object retrieved from the DB
lineOrder.field1 = "empty"
lineOrder.save()
但是当我调试应用程序时,我发现 无论我有多少次迭代,create_or_Get()
方法总是 return 第一行的 PK .
为什么会出现这种行为?
我想 peewee 没有意识到这一限制?您可能需要编写自己的实现,因为无论如何您似乎想要一些不同的东西。
只是:
try:
with db.atomic():
return ProductOrderItem.create(order=orderObj, orderline=idx), True
except IntegrityError:
return ProductOrderItem.get(
(ProductOrderItem.order == orderObj) &
(ProductOrderItem.orderline == idx))
我有这样一个模型:
class ProductOrderItem(BaseModel):
prodorder = peewee.ForeignKeyField(modprodord.ProductOrder, related_name='items')
cid = peewee.IntegerField(null=False)
class Meta:
db_table = 'TBWOHPARGDET'
primary_key = CompositeKey('prodorder','cid')
这样做的目的是用这样的东西构建一个 table:
|ID_ORDER|ID_ORDERLINE|
| 1| 1|
| 1| 2|
| 1| 3|
| 2| 1|
Appart,在我的BO层,我想判断这个对象之前是否创建过。所以我使用 create_or_get(method)
只是为了接收 created 变量或对应于提供的 PK 字段的 lineOrder - 我的意思是,通过方法在数据库中找到的对象 - :
for idx,x in enumerate(collection):
lineOrder, created = ProductOrderItem.create_or_get(order=orderObj,orderline=idx,[rest_of_fields])
if(created): # this is when the object was created
else: # this is when the object with those PK's was found in database
# this is where I want to add the rest of fields, in other this linea I have the object retrieved from the DB
lineOrder.field1 = "empty"
lineOrder.save()
但是当我调试应用程序时,我发现 无论我有多少次迭代,create_or_Get()
方法总是 return 第一行的 PK .
为什么会出现这种行为?
我想 peewee 没有意识到这一限制?您可能需要编写自己的实现,因为无论如何您似乎想要一些不同的东西。
只是:
try:
with db.atomic():
return ProductOrderItem.create(order=orderObj, orderline=idx), True
except IntegrityError:
return ProductOrderItem.get(
(ProductOrderItem.order == orderObj) &
(ProductOrderItem.orderline == idx))