Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass enum to ndb.Model field in python

I find How can I represent an 'Enum' in Python? for how to create enum in python. I have a field in my ndb.Model that I want to accept one of my enum values. Do I simply set the field to StringProperty? My enum is

def enum(**enums):
    return type('Enum', (), enums)

ALPHA = enum(A="A", B="B", C="C", D="D")
like image 669
Katedral Pillon Avatar asked Feb 17 '23 02:02

Katedral Pillon


1 Answers

This is fully supported in the ProtoRPC Python API and it's not worth rolling your own.

A simple Enum would look like the following:

from protorpc import messages 

class Alpha(messages.Enum):
    A = 0
    B = 1
    C = 2
    D = 3

As it turns out, ndb has msgprop module for storing protorpc objects and this is documented.

So to store your Alpha enum, you'd do the following:

from google.appengine.ext import ndb
from google.appengine.ext.ndb import msgprop

class Part(ndb.Model):
    alpha = msgprop.EnumProperty(Alpha, required=True)
    ...

EDIT: As pointed out by hadware, a msgprop.EnumProperty is not indexed by default. If you want to perform queries over such properties you'd need to define the property as

    alpha = msgprop.EnumProperty(Alpha, required=True, indexed=True)

and then perform queries

ndb.query(Part.alpha == Alpha.B)

or use any value other than Alpha.B.

like image 145
bossylobster Avatar answered May 05 '23 19:05

bossylobster