3

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")
Community
  • 1
  • 1
Katedral Pillon
  • 14,534
  • 25
  • 99
  • 199

1 Answers1

8

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.

Community
  • 1
  • 1
bossylobster
  • 9,993
  • 1
  • 42
  • 61
  • 1
    It is possible to query on the msgprop, and on the enum? – Hadrien Titeux Jul 21 '14 at 21:03
  • Have you tried to query on the `msgprop`? I'd guess it works just like an integer and you could use `ndb.query(Part.alpha == Alpha.B)`. You should start up a dev server and see for yourself. – bossylobster Jul 22 '14 at 00:28
  • I actually did it while asking the question, and yes it worked exactly as you suggested it, on one condition: **the `msgprop.EnumProperty(SomeEnumType)` had to be indexed** (and thus set this way: `msgprop.EnumProperty(SomeEnumType, indexed = True)`). You might want to add this to your answer to make it richer ;) – Hadrien Titeux Jul 22 '14 at 00:43
  • Good call. Thanks for checking. – bossylobster Jul 22 '14 at 01:18