peewee custom field - define allowed values
<p>Two cases:</p>

<p>1.) I'd like to define an attribute (val) that can take the integers 0, 1, or 2 only.</p>

<pre><code>class Trinary(Model):
    """val should accept the values 0, 1 or 2 only"""
    val = IntegerField()
</code></pre>

<p>2.) I'd like to define an attribute (val) that can take specific strings only, for example ["strawberry", "peach", "apple"]</p>

<pre><code>class Fruit(Model):
    """val should accept the values "strawberry", "peach" or "apple" only """
    val = ???
</code></pre>

<p>Is is possible to implement such a restriction using peewee?</p>

<p>Thanks for your help!</p>

<p>Muff</p>

<p>The objects <code>IntegerField</code> etc. are classes, and can be subclassed (<a href="http://docs.peewee-orm.com/en/latest/peewee/models.html#custom-fields" rel="nofollow">documentation</a>):</p>

<p>The classes should define <code>db_value</code> to convert from python to database,
and <code>python_value</code> for the other way round</p>

<pre><code>class TrinaryField(IntegerField):
        def db_value(self, value):
            if value not in [0,1,2]:
                raise TypeError("Non-trinary digit")
            return super().db_field(value)  # call 
</code></pre>

python python-3.x peewee