Search code examples
pythonpython-3.xenumsponyorm

Using enum inside Pony ORM query


I have an entity and an enum declared as follow :

class SupplierModel(db.Entity):
    id = PrimaryKey(int, unsigned=True, auto=True)
    ...

class Supplier(IntEnum):
    MyFirstSupplier = 1
    MySecondSupplier = 2
    ...

My goal isn't to store every suppliers (which are created and deleted dynamically by users), but for few of them, i have some "custom" features in my business logic so i need to identity them. Those specific supplier entities are basically immutable so i'm storing their primary keys in this enum.

So far so good, until i'm trying to do things like this :

select(sup for sup in SupplierModel if sup.id == Supplier.MyFirstSupplier)

I get this error : Expression Supplier.MyFirstSupplier has unsupported type 'Supplier'

Is there anything am i doing wrong ?

Thank you for your help.


Solution

  • The problem isn't with PonyORM but rather in how you access the IntEnum values. Check out the Python Enum docs for examples.

    Supplier.MyFirstSupplier returns only the enum <Supplier.MyFirstSupplier: 1>, not the value 1 as you expect. You need to append .value like this:

    select(sup for sup in SupplierModel if sup.id == Supplier.MyFirstSupplier.value)
    

    I find it helpful to quickly test these in an interactive Python prompt in console, it immediately becomes clear then what's going wrong:

    >>> Supplier.MyFirstSupplier
    <Supplier.MyFirstSupplier: 1>
    >>> type(Supplier.MyFirstSupplier)
    <enum 'Supplier'>
    >>> Supplier.MyFirstSupplier.value
    1