Search code examples
python-3.xpeewee

Peewee: create_or_get() error in Model with CompositeKey


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?


Solution

  • I guess peewee isn't picking up on the constraint? You may need to write your own implementation since it seems you want something a bit different anyways.

    What about just:

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