schematics/schematics

What is the right way to use 'choices' with compound types

levsh opened this issue · 3 comments

levsh commented

Hello! I need a list type with limited set of values so i am trying following code but it not working

In [1]: import schematics

In [2]: schematics.__version__
Out[2]: '2.0.1'

In [3]: from schematics import models

In [4]: from schematics import types

In [5]: class M(models.Model):
   ...:     l = types.compound.ListType(types.StringType, choices=['a', 'b'])
   ...:

In [6]: m = M()

In [7]: m.l = ['a']

In [8]: m.validate()
---------------------------------------------------------------------------
DataError                                 Traceback (most recent call last)
<ipython-input-8-8a07fc25181e> in <module>()
----> 1 m.validate()

/usr/local/lib/python3.6/site-packages/schematics/models.py in validate(self, partial, convert, app_data, **kwargs)
    252         try:
    253             data = self._convert(validate=True,
--> 254                 partial=partial, convert=convert, app_data=app_data, **kwargs)
    255             self._data.valid = data
    256         except DataError as e:

/usr/local/lib/python3.6/site-packages/schematics/models.py in _convert(self, raw_data, context, **kwargs)
    293         should_validate = getattr(context, 'validate', kwargs.get('validate', False))
    294         func = validate if should_validate else convert
--> 295         return func(self._schema, self, raw_data=raw_data, oo=True, context=context, **kwargs)
    296
    297     def export(self, field_converter=None, role=None, app_data=None, **kwargs):

/usr/local/lib/python3.6/site-packages/schematics/validate.py in validate(schema, mutable, raw_data, trusted_data, partial, strict, convert, context, **kwargs)
     63
     64     if errors:
---> 65         raise DataError(errors, data)
     66
     67     return data

DataError: {"l": ["Value must be one of ['a', 'b']."]}

What am I doing wrong?

try
m.l = 'a'

levsh commented

@yzongyue thanks for help. But M.l is a list type so i expect it is possible to have more than one value, example m.l = ['a', 'b']

i understand now...
try:

class M(models.Model):
l = types.compound.ListType(types.StringType(choices=['a', 'b']))