So I can create Django model like this:
from django.db import models
class Something(models.Model):
title = models.TextField(max_length=200)
and I can work with it like this:
thing = Something()
#set title
thing.title = "First thing"
#get title
thing.title
All works as it should but I’d like to understand HOW it works.
title = models.TextField(max_length=200)
in non-Django Python code above line defines class variable title of type models.TextField and I could access it also like this: thing.__class__.title(link)
But in Django when I create instance of Something I suddenly have a title attribute where I can get/set text. And cannot access it with thing.__class__.title So clearly when doing thing.title I’m not accessing class variable “title” but some generated attribute/property, or?
I know that fields ended up in thing._meta.fields but how? What’s going on and how?
1, Does Django create property “title” behind the scenes?
2, What happened to class variable “title”?
I think its hard to beat what Django documentation has to say on this.
Basically a metaclass defines how a class itself will be created. During creation, additional attributes/methods/anything can be bound to that class. The example this stackoverflow answer gives, capitalizes all the attributes of a class
In a similar way, Django’s metaclass for Models can digest the attributes you’ve applied to the class and add various useful attributes for validation/etc, including even methods and what-not.