Why Python is best for Django?, Job trends in Django, Learn Django Online
The Django Book - Chapter 5: Models
-
Upload
sharon-chen -
Category
Engineering
-
view
248 -
download
4
Transcript of The Django Book - Chapter 5: Models
The Django Book—Models
Sharre Chen
http://django-book.readthedocs.org/en/latest/index.html
MVC
M(Model): data access logic, is handled by Django’s database layer
V(View): business logic, is handled by views and templates.
C(Controller): presentation logic, is handled by the framework itself by following your URLconf and calling the appropriate Python function.
MTV
M(Model): data access layer.
T(Template): the presentation layer.
V(View): business logic layer.
Configuring the Database
• In settings.py:
Example for MySQL: DATABASE_ENGINE = 'mysql'DATABASE_NAME = 'mydb'DATABASE_USER= 'user'DATABASE_PASSWORD = 'password'DATABASE_HOST = ‘/var/run/mysql'!Try if setting is correct:$ python manage.py shell>>> from django.db import connection>>> cursor = connection.cursor()
What’s the difference between a project and an app?
• A project is an instance of a certain set of Django apps, plus the configuration for those apps.
• An app is a portable set of Django functionality, usually including models and views, that lives together in a single Python package.
★ if you’re using Django’s database layer (models), you must create a Django app.
Check models’ syntax
checks whether your models’ syntax and logic are correct:
$ python manage.py validate
check create table sqlIf your models are valid, run the following command for Django to generate CREATE TABLE statements for your models in the books app (before migration):
$ python manage.py sqlall books
commit the SQL to database
$ python manage.py syncdb
!
!
★ Note that syncdb does not sync changes in models or deletions of models.
Basic data access
If you want to create an object and save it to the database in a single step, use the objects.create() method.
Selecting Objects
if you type command:
This roughly translates to this SQL:
!
✦ Zen of Python: “Explicit is better than implicit.”
Filtering Data: LIKE
filter data:
!
here, the __contains part gets translated by Django into a SQL LIKE statement:
!
Ordering Data
get ordered data:
SQL will be:
!
To order by multiple fields:
!
specify reverse ordering:
Updating Multiple Objects in One Statement
update a filed:
!
!
update will return success updated object number: