Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding django

Tags:

python

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?

like image 323
Matt Cremeens Avatar asked Dec 14 '22 17:12

Matt Cremeens


2 Answers

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.

like image 93
nima Avatar answered Jan 03 '23 04:01

nima


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.

like image 45
Andrew Dunai Avatar answered Jan 03 '23 05:01

Andrew Dunai