Skip to content Skip to sidebar Skip to footer

Django Models & Python Class Attributes

The tutorial on the django website shows this code for the models: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_d

Solution 1:

Have a look at the Model class under django/db/models.py. There the class attributes are turned to instance attributes via something like

setattr(self, field.attname, val)

One might recommend the whole file (ModelBase and Model class) as an excellent hands-on example on metaclasses.

Solution 2:

It's done with metaclasses - very clever stuff. I'd recommend Marty Alchin's excellent book Pro Django if you want to learn more.

Solution 3:

In Python, a class attribute is always also an instance attribute:

classC(object):
    a = 1defshow_a(self):
        print self.a # <- works

But in django it is further complicated by the fact that Model classes have special metaclasses, so be careful to your assumptions!

Solution 4:

A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched.

http://docs.python.org/reference/datamodel.html

Post a Comment for "Django Models & Python Class Attributes"