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")
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With