Matt Cremeens
Matt Cremeens

Reputation: 5151

Understanding django

New at this and trying to learn python and django. I'll cut right to the chase. I'm reading the django tutorial on the main site and I see that you can set up a database in django with class variables like those given here

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

Later in the tutorial, a Poll object is created using

p = Poll(question="What's new?", pub_date=timezone.now())

My question is: it appears as though strings are being passed using named arguments, yet in the class, these appear to be objects constructed using models. So how does django convert the string, "What's new?", to become a question object?

Upvotes: 4

Views: 583

Answers (3)

Andrew Dunai
Andrew Dunai

Reputation: 3129

The trick is that question and pub_date are not typical object properties: they are class properties. Django uses them to understand what you want the model to look like.

Later, when you create a Poll class that extends models.Model, Django takes a look at question and pub_date class properties and creates an object that stores them as object properties.

For example, let's try to create our own ORM:

class CoolModel:
    def __init__(self, **kwargs):
        self.values = {}
        for field, value in kwargs.items():
            if getattr(self, field, None):
                self.values[field] = value
            else:
                raise Exception('Unknown model field - {}!'.format(field))

class CoolField(object):
    pass

# Here we create our model:

class Poll(CoolModel):
    name = CoolField()
    date = CoolField()

m1 = Poll(name='test', date='yesterday?')
print m1.values  # Prints '{"name": "test", "date": "yesterday"}'
m2 = Poll(name='test2', some_field="wtf") # Raises Exception:
                                               # Unknown model field = some_field!

That's how Django does it.

Upvotes: 5

nima
nima

Reputation: 6733

When you define your model class you are just defining your model schema for Django. Django uses this information to create a table and hold your objects. So, when you say:

question = models.CharField(max_length=200)

a text field is created in database and Poll objects will have a question field that hold a string.

Upvotes: 5

Serafeim
Serafeim

Reputation: 15084

It doesn't convert it to anything since from the provided Poll class, question is defined as a CharField (text) and not as an object. Django won't do any magic !

Upvotes: 2

Related Questions