Peewee: create_or_get() error in Model with CompositeKey

时间:2016-02-03 02:49:18

标签: python-3.x peewee

I have a Model like this:

    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')

The purpose on this is to build a table with something like this:

    |ID_ORDER|ID_ORDERLINE|
    |       1|           1|
    |       1|           2|
    |       1|           3|
    |       2|           1|

Appart, in my BO layer, I want to determine if this object was previously created or not. So I used create_or_get(method) just to receive the created variable OR the lineOrder which corresponds to the PK fields provided -I mean, the object which was found in the DB by the method-:

   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()

But when I debug the app I found that no matter how many iterations I have, create_or_Get() method always return the PK's of the first row.

Why is this behaviour?

1 个答案:

答案 0 :(得分:2)

我猜peewee并没有接受约束?您可能需要编写自己的实现,因为无论如何您似乎想要一些不同的东西。

仅仅是:

try:
    with db.atomic():
        return ProductOrderItem.create(order=orderObj, orderline=idx), True
except IntegrityError:
    return ProductOrderItem.get(
        (ProductOrderItem.order == orderObj) &
        (ProductOrderItem.orderline == idx))