1

I'm new to both Python and Django, and I'm trying to get a sense for how Django's Model Class (and classes in general) work.

If you create a new model:

from django.db import models class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) 

Now you can do things such as:

>>> from myapp.models import Book >>> book = Book(title="a new book", author="bob") >>> book.save() >>> print book.title a new book 

Great, it works. But the way that the Book class inherits from the Model class is a bit confusing. It would appear that title and author act as instance variables, but looking at the class definition it would appear that they are static.

from django.db import models class Book(models.Model): def __init__(self, *args, **kwargs): self.title = models.Charfield(max_length=200) self.author = models.CharField(max_length=200) super(Book, self).__init__() 

To me, that seems to be the more intuitive way to declare the class, but Django does not pick these schema changes up when I run a migration. I understand why this doesn't work, I'm just not sure I understand why the above method does work.

Thanks in advance.

1
  • 2
    Django's model classes are not a good way to learn about classes in general. Django's model class uses meta classes and descriptors to work (both are relatively large topics). Commented Nov 17, 2014 at 22:44

2 Answers 2

2

This is really too complex to answer in a question here. The quick answer is, it's all done with metaclasses, but for the full explanation you should read Marty Alchin's book Pro Django.

The point is that you don't want self.title, for example, to be a field instance: you want it to be whatever the value of the title is. So, (simplifying quite a bit) when the model instance is constructed from the database, the metaclass goes through the class-level Field attributes, and for each one it sets an instance-level attribute to the value of the db column. On save, of course, it does the reverse.

Sign up to request clarification or add additional context in comments.

Comments

0

class in python and how model in django are defined is different. The definition of model in django just use the syntax of python as a descriptive language for field and database related informations, then django introspect the class for extract this informations. But for the rest it's a normal python class, you can define method etc ...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.