Skip to content
This repository was archived by the owner on Aug 19, 2025. It is now read-only.
This repository was archived by the owner on Aug 19, 2025. It is now read-only.

Support choices #35

Description

@Lynskylate

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions