orm icon indicating copy to clipboard operation
orm copied to clipboard

Support choices

Open Lynskylate opened this issue 5 years ago • 2 comments

Django ORM field can have a choice argument to validate data.

from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    )
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

    def is_upperclass(self):
        return self.year_in_school in (self.JUNIOR, self.SENIOR)

I tried to add choices argument, but I don't know how to do it right. My code looks like below.

class ChoiceField(ModelField, typesystem.Choice):
    def __init__(self, **kwargs):
        if 'choices' in kwargs:
            choices = kwargs.pop('choices')
            super(typesystem.Choice, self).__init__(choices=choices)
        super().__init__(**kwargs)

class String(ChoiceField, typesystem.String):
     def __init__(self, **kwargs):
        ....
     def validate(self, value, *, strict:bool = False):
        # overload validate
        if self.choices:
            super(typesystem.Choice, self).validate(value)
        return super(typesystem.String, self).validate(value)

Although we can use Choice schema class to validate choice data, the inheritance will make us confused. and we have to overload validate function

Lynskylate avatar May 02 '19 07:05 Lynskylate

Yup that'd be very welcome. Happy to consider any pull requests towards resolving this.

tomchristie avatar May 02 '19 11:05 tomchristie

Hi,

This project seems stale and from what I saw on encode page it's not a priority right now. Since I was tired with reinventing the wheel and needed something as soon as possible I created ormar package, that was inspired by this one.

Ormar bases its validation on pydantic so it can be used directly with fastapi as response and request models.

This issue was implemented in ormar, so feel free to check it out: https://github.com/collerek/ormar

collerek avatar Oct 22 '20 12:10 collerek