Django-ORM练习笔记

图书信息系统

表结构设计

 1 # 书
 2 class Book(models.Model):
 3     title = models.CharField(max_length=32)
 4     publish_date = models.DateField(auto_now_add=True)
 5     price = models.DecimalField(max_digits=5, decimal_places=2)
 6     memo = models.TextField(null=True)
 7     # 创建外键,关联publish
 8     publisher = models.ForeignKey(to="Publisher")
 9     # 创建多对多关联author
10     author = models.ManyToManyField(to="Author")
11 
12     def __str__(self):
13         return self.title
14 
15 
16 # 出版社
17 class Publisher(models.Model):
18     name = models.CharField(max_length=32)
19     city = models.CharField(max_length=32)
20 
21     def __str__(self):
22         return self.name
23 
24 
25 # 作者
26 class Author(models.Model):
27     name = models.CharField(max_length=32)
28     age = models.IntegerField()
29     phone = models.CharField(max_length=11)
30     detail = models.OneToOneField(to="AuthorDetail")
31 
32     def __str__(self):
33         return self.name
34 
35 
36 # 作者详情
37 class AuthorDetail(models.Model):
38     addr = models.CharField(max_length=64)
39     email = models.EmailField()

 

练习笔记orm2.py(在manage.py同级目录)

 1 # !/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # author:大西瓜
 4 
 5 import os
 6 if __name__ == '__main__':
 7     # 加载Django项目的配置信息
 8     os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Paulsiteday63.settings")
 9     # 导入Django,并启动Django项目
10 
11     import django
12     django.setup()
13 
14     from app01 import models
15 
16     # 查找所有书名里包含童话的书
17     ret = models.Book.objects.filter(title__contains="童话")
18     print(ret)
19 
20     # 查找出版日期是2018年的书
21     # ret = models.Book.objects.filter(publisher_date__year=2018)
22     # print(ret)
23 
24     # 查找价格大于10元的书
25     ret = models.Book.objects.filter(price__gt=10)
26     print(ret)
27 
28     # 找到在沙河的出版社
29     ret = models.Publisher.objects.filter(addr="沙河")
30     print(ret)
31 
32     # distinct
33     # 查所有书关联的出版社
34     ret = models.Book.objects.all().values_list("publisher__name")
35     print(ret)
36     print(ret.distinct()) # 去重
37 
38     # 将所有的书按照价格倒序排序
39     ret = models.Book.objects.all().order_by("price") # 正向排序
40     print(ret)
41 
42     ret = models.Book.objects.all().order_by("price").reverse() # 倒序排序
43     print(ret)
44     # 或
45     ret = models.Book.objects.all().order_by("-price") # 倒序排序 支持负号表示倒序
46     print(ret)
47 
48     # 查询书名是童话第一版的书的出版社的city
49     ret = models.Book.objects.filter(title="童话第一版").values("publisher__addr")
50     print(ret)
51 
52     # 查询书名是沙河异闻录的书的作者的爱好(跨两张表)
53     ret = models.Book.objects.filter(title="沙河异闻录").values("authors__detail__hobby")
54     print(ret)

 

posted @ 2018-09-18 16:04  大西瓜Paul  阅读(86)  评论(0编辑  收藏  举报
/*增加返回顶部按钮*/ 返回顶部 /*给标题增加蓝色背景长条*/