Choices "django like" with sqlalchemy

2,344 views
Skip to first unread message

Artur Felipe Sousa

unread,
May 17, 2012, 12:07:40 PM5/17/12
to sqlal...@googlegroups.com
Hey guys!

Which way you take to map some custom data (not in database) with sqlalchemy?

In django it will be:
GENDER_CHOICES = (
   
('M', 'Male'),
   
('F', 'Female'),
)
class Foo(models.Model):
    gender
= models.CharField(max_length=1, choices=GENDER_CHOICES
)

I saw an implamantion of it using types in http://stackoverflow.com/questions/6262943/sqlalchemy-how-to-make-django-choices-using-sqlalchemy:

import
sqlalchemy.types as types
class ChoiceType(types.TypeDecorator):
    impl
= types.String

   
def __init__(self, choices, **kw):
       
self.choices = dict(choices)
       
super(ChoiceType, self).__init__(**kw)

   
def process_bind_param(self, value, dialect):
       
return [k for k, v in self.choices.iteritems() if v == value][0]

   
def process_result_value(self, value, dialect):
       
return self.choices[value]


Is it alright? Or you guys do it another way?

Thanks a lot!

Michael Bayer

unread,
May 17, 2012, 12:29:29 PM5/17/12
to sqlal...@googlegroups.com
that's the basic idea and for a more complete example see the blog post at http://techspot.zzzeek.org/2011/01/14/the-enum-recipe/ .


--
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To view this discussion on the web visit https://groups.google.com/d/msg/sqlalchemy/-/M5Qi6UMvI-IJ.
To post to this group, send email to sqlal...@googlegroups.com.
To unsubscribe from this group, send email to sqlalchemy+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.

Reply all
Reply to author
Forward
0 new messages