Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()

Now, each of those attribute, is a class attribute, right? So, the same attribute should be shared by all instances of the class. A bit later, they present this code:

class Poll(models.Model):
    # ...
    def __unicode__(self):
        return self.question

class Choice(models.Model):
    # ...
    def __unicode__(self):
        return self.choice

How did they turn from class attributes into instance attributes? Did I get class attributes wrong?

like image 600
Geo Avatar asked May 25 '10 10:05

Geo


People also ask

What are models in Django used for?

Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc.

What is Django model class?

Advertisements. A model is a class that represents table or collection in our DB, and where every attribute of the class is a field of the table or collection. Models are defined in the app/models.py (in our example: myapp/models.py)

What is __ str __ In Django model?

The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object.


1 Answers

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.

like image 170
miku Avatar answered Oct 03 '22 13:10

miku