From 4760295d6a275b0178a8cfb743a0120cbc04a351 Mon Sep 17 00:00:00 2001 From: Lance Edgar Date: Fri, 9 Feb 2018 15:04:22 -0600 Subject: [PATCH] Add some basic ORM object field types for new forms --- tailbone/forms2/types.py | 62 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/tailbone/forms2/types.py b/tailbone/forms2/types.py index 977b8bc6..e9fcdb59 100644 --- a/tailbone/forms2/types.py +++ b/tailbone/forms2/types.py @@ -2,7 +2,7 @@ ################################################################################ # # Rattail -- Retail Software Framework -# Copyright © 2010-2017 Lance Edgar +# Copyright © 2010-2018 Lance Edgar # # This file is part of Rattail. # @@ -26,8 +26,12 @@ Form Schema Types from __future__ import unicode_literals, absolute_import +from rattail.db import model + import colander +from tailbone.db import Session + class JQueryTime(colander.Time): """ @@ -52,3 +56,59 @@ class JQueryTime(colander.Time): # re-try first format, for "better" error message return colander.timeparse(cstruct, formats[0]) + + +class ObjectType(colander.SchemaType): + """ + Custom schema type for scalar ORM relationship fields. + """ + model_class = None + + @property + def model_title(self): + self.model_class.get_model_title() + + @property + def session(self): + return Session() + + def serialize(self, node, appstruct): + if appstruct is colander.null: + return colander.null + return six.text_type(appstruct) + + def deserialize(self, node, cstruct): + if not cstruct: + return None + obj = self.session.query(self.model_class).get(cstruct) + if not obj: + raise colander.Invalid(node, "{} not found".format(self.model_title)) + return obj + + +class StoreType(ObjectType): + """ + Custom schema type for store field. + """ + model_class = model.Store + + +class CustomerType(ObjectType): + """ + Custom schema type for customer field. + """ + model_class = model.Customer + + +class ProductType(ObjectType): + """ + Custom schema type for product relationship field. + """ + model_class = model.Product + + +class UserType(ObjectType): + """ + Custom schema type for user field. + """ + model_class = model.User