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

Open
Open

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

  1. lovelydinosaur commented on May 2, 2019

    @lovelydinosaur
    Member

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

  2. collerek commented on Oct 22, 2020

    @collerek

    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

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