django学习笔记(二)

1) 模板中的{% include %}。

{% include 'nav.html' %}

2) django也支持类似rails中layout的概念,具体来说,在django中是通过模板的继承来实现的。

base.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My helpful timestamp site</h1>
{% block content %}{% endblock %}
{% block footer %}
<hr>
<p>Thanks for visiting my site.</p>
{% endblock %}
</body>
</html>

===================================

current_datetime.html:

{% extends "base.html" %}

{% block title %}The current time{% endblock %}

{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}


===================================

hours_ahead.html:

{% extends "base.html" %}

{% block title %}Future time{% endblock %}

{% block content %}
<p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p>
{% endblock %}

===================================

需要注意的是:

《1》 如果在模板中使用 {% extends %} ,必须保证其为模板中的第一个模板标记。 否则,模板继承将不起作用。
《2》不允许在同一个模板中定义多个同名的 {% block %} 。


3) MySQLdb的典型调用。

from django.shortcuts import render_to_response
import MySQLdb

def book_list(request):
db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
cursor = db.cursor()
cursor.execute('SELECT name FROM books ORDER BY name')
names = [row[0] for row in cursor.fetchall()]
db.close()
return render_to_response('book_list.html', {'names': names})

4)新建app。

python manage.py startapp myapp

5)验证模型是否正常。

python manage.py validate

6)models.py的典型用法。

from django.db import models

class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()

class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()

编辑完成后,在设置文件中加载app。

INSTALLED_APPS = (
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.sites',
'mysite.books',
)

再运行

python manage.py sqlall books

可以查看将会生成的sql语句。

运行

python manage.py syncdb

就可以生成相应的数据库表了。

7)查询数据库中的所有记录。

Publisher.objects.all()

这个方法返回返回数据库中所有的记录。 尽管这个对象 看起来 象一个列表(list),它实际是一个 QuerySet 对象, 这个对象是数据库中一些记录的集合。

8)数据过滤。

Publisher.objects.filter(name='Apress')

Publisher.objects.filter(country="U.S.A.", state_province="CA")

其相当于

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE country = 'U.S.A.'
AND state_province = 'CA';

除了精确的=操作,也可以实现模糊的like操作

Publisher.objects.filter(name__contains="press")

相当于

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE name LIKE '%press%';

其他的一些查找类型有:icontains(大小写无关的LIKE),startswith和endswith, 还有range(SQLBETWEEN查询)。

9) 对返回结果排序。

Publisher.objects.order_by("name")

还可以对多项字段进行排序

Publisher.objects.order_by("state_province", "address")

我们还可以指定逆向排序,在前面加一个减号 - 前缀:

Publisher.objects.order_by("-name")

尽管很灵活,但是每次都要用 order_by() 显得有点啰嗦。 大多数时间你通常只会对某些 字段进行排序。 在这种情况下,Django让你可以指定模型的缺省排序方式:

class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()

def __unicode__(self):
return self.name

class Meta:
ordering = ['name']


10) 连锁查询。

Publisher.objects.filter(country="U.S.A.").order_by("-name")

相当于

SELECT id, name, address, city, state_province, country, website

FROM books_publisher
WHERE country = 'U.S.A'
ORDER BY name DESC;

11) 限制返回的数据。

Publisher.objects.order_by('name')[0]

相当于

SELECT id, name, address, city, state_province, country, website

FROM books_publisher
ORDER BY name
LIMIT 1;

Publisher.objects.order_by('name')[0:2]

相当于

SELECT id, name, address, city, state_province, country, website
FROM books_publisher
ORDER BY name
OFFSET 0 LIMIT 2;

注意,不支持Python的负索引。

12)更新多个对象的字段值。

Publisher.objects.all().update(country='USA')

可以对多条数据批量修改。

13)删除多条数据。

Publisher.objects.filter(country='USA').delete()
Publisher.objects.all().delete()

14)添加数据库。

python manage.py syncdb

15) 添加应用。

from django.contrib import admin
from mysite.books.models import Publisher, Author, Book

admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)

16) 使用 count 方法可以确定一个 QuerySet 中有多少记录。Python 的 len 方法会进行全面的计算,然后统计那些以记录形式返回的行数,而 count 方法执行的则是真正的 SQL COUNT 操作,其速度更快。我们这样做,数据库管理员会感激我们的。

>>> from jobs.models import Job
>>> print "Count = ", Job.objects.count()       # GOOD!
>>> print "Count = ", len(Job.objects.all())    # BAD!

原文地址:https://www.cnblogs.com/cly84920/p/4426697.html