mardi 9 juillet 2019

What's behind the mechanism of Django models and fields?

What is the Django/Python mechanism behind the Django model/field part of framework?

To be exact, I am looking for a hint on how Django parses (?) class definition and then knows which fields are required?

from django.db import models


class Car(models.Model):
    name = models.CharField(max_length=255, null=True, blank=True)
    year_of_production = models.DateField(null=True)
    # the rest of fields...

I think the same mechanism is behind Django Forms framework or DRF serializers. I checked repos of these projects but I still can't find any reasonable starting point.

There's a architectural problem under my question. I think I need to implement something similar to this mechanism:

class Field:
    def __init__(self, label: str, required: bool = True, **kwargs):
        self.label, self.required = label, required


class CharField(Field):
    def __init__(self, max_length: int, **kwargs):
        self.max_length = max_length
        super().__init__(**kwargs)

class DateField(Field):
    ...

class BooleanField(Field):
    ...

class Model:
    # the mechanisms I do not understand

class MyModelInstance(Model):
    name = CharField(...)
    # etc.    

What I need is really simple solution that knows that field is required. But as I stated before I am not that advanced and I would really appreciate any hints.

Aucun commentaire:

Enregistrer un commentaire