Django 里更关注的是模型(Model)、模板(Template)和视图(Views),Django 也被称为 MTV 框架 。
数据库配置文件settings.py
如果你使用了Django的数据库层(模型),你 必须创建一个Django app。
python manage.py startapp books
第一个模型:
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()
模型安装:
在setting.py里的INSTALLED_APPS中添加app名
同步到数据库:
python manage.py makemigrations
python manage.py migrate
基本数据访问:
>>> from books.models import Publisher
>>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
... city='Berkeley', state_province='CA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p1.save()
>>> p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',
... city='Cambridge', state_province='MA', country='U.S.A.',
... website='http://www.oreilly.com/')
>>> p2.save()
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
[<Publisher: Publisher object>, <Publisher: Publisher object>]
# 如果需要一步完成对象的创建与存储至数据库,就使用`` objects.create()`` 方法。
>>> p1 = Publisher.objects.create(name='Apress',
... address='2855 Telegraph Avenue',
... city='Berkeley', state_province='CA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p2 = Publisher.objects.create(name="O'Reilly",
... address='10 Fawcett St.', city='Cambridge',
... state_province='MA', country='U.S.A.',
... website='http://www.oreilly.com/')
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
[<Publisher: Publisher object>, <Publisher: Publisher object>]
# 当我们打印,列出的是地址,而不是具体内容,无法区分哪个是哪个
# 我们可以简单解决这个问题,只需要为Publisher 对象添加一个方法 __unicode__() 。
# __unicode__() 方法告诉Python如何将对象以unicode的方式显示出来。在python3中用__str__()方法来实现。****很重要******
#代码如下:
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**
插入和更新数据:
# 插入数据
>>> p = Publisher(name='Apress',
... address='2855 Telegraph Ave.',
... city='Berkeley',
... state_province='CA',
... country='U.S.A.',
... website='http://www.apress.com/')
# 保存到数据库
>>> p.save()
# 更新数据
>>> p.name = 'Apress Publishing'
>>> p.save()
选择对象:
>>> Publisher.objects.all()
[<Publisher: Apress>, <Publisher: O'Reilly>]
数据过滤:
>>> Publisher.objects.filter(name='Apress')
[<Publisher: Apress>]
>>> Publisher.objects.filter(country="U.S.A.", state_province="CA")
[<Publisher: Apress>]
# 在 name 和 contains 之间有双下划线。和Python一样,Django也使用双下划线来表明会进行
# 一些魔术般的操作。这里,contains部分会被Django翻译成LIKE语句:
# 其他的一些查找类型有:icontains(大小写无关的LIKE),startswith和endswith, 还有range(SQLBETWEEN查询)。
>>> Publisher.objects.filter(name__contains="press")
[<Publisher: Apress>]
等同:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher
WHERE name LIKE '%press%';
获取单个对象:
>>> Publisher.objects.get(name="Apress")
<Publisher: Apress>
try:
p = Publisher.objects.get(name='Apress')
except Publisher.DoesNotExist:
print "Apress isn't in the database yet."
else:
print "Apress is in the database."
数据排序:
>>> Publisher.objects.order_by("name")
[<Publisher: Apress>, <Publisher: O'Reilly>]
# 还可以指定逆向排序,在前面加一个减号 ‐ 前缀:
>>> Publisher.objects.order_by("‐name")
[<Publisher: O'Reilly>, <Publisher: Apress>]
尽管很灵活,但是每次都要用 order_by() 显得有点啰嗦。 大多数时间你通常只会对某些 字段进行排序。 在这种情况下,Django让你可以指定模型的缺省排序方式,使用 Meta 类:
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']**
连锁查询:
>>> Publisher.objects.filter(country="U.S.A.").order_by("‐name")
[<Publisher: O'Reilly>, <Publisher: Apress>]
限制返回的数据:
>>> Publisher.objects.order_by('name')[0]
<Publisher: Apress>
这相当于:
SELECT id, name, address, city, state_province, country, website
FROM books_publisher
ORDER BY name
LIMIT 1;
>>> Publisher.objects.order_by('name')[0:2]
# 注意,不支持Python的负索引
更新多个对象:
方式一:
>>> p = Publisher.objects.get(name='Apress')
>>> p.name = 'Apress Publishing'
>>> p.save()
方式二:
# update()方法对于任何结果集(QuerySet)均有效,这意味着你可以同时更新多条记录。
>>> Publisher.objects.filter(id=52).update(name='Apress Publishing')
>>> Publisher.objects.all().update(country='USA')
2
# update()方法会返回一个整型数值,表示受影响的记录条数。
删除对象:
删除数据库中的对象只需调用该对象的delete()方法即可:
>>> p = Publisher.objects.get(name="O'Reilly")
>>> p.delete()
>>> Publisher.objects.all()
[<Publisher: Apress Publishing>]
同样我们可以在结果集上调用delete()方法同时删除多条记录。这一点与我们上一小节提到的update()方法相似:
>>> Publisher.objects.filter(country='USA').delete()
>>> Publisher.objects.all().delete()
>>> Publisher.objects.all()
[]
删除数据时要谨慎! 为了预防误删除掉某一个表内的所有数据,Django要求在删除表内所有数据时显示使用all()。 比如,下面的操作将会出错:
>>> Publisher.objects.delete()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Manager' object has no attribute 'delete'
而一旦使用all()方法,所有数据将会被删除:
>>> Publisher.objects.all().delete()
如果只需要删除部分的数据,就不需要调用all()方法。再看一下之前的例子:
>>> Publisher.objects.filter(country='USA').delete()
归纳:
1.数据模型的格式
2.数据模型的使用,添加 删除 查找 修改 排序
后续学习掌握方向:
django数据模型 类型
元类
网友评论