创建表结构
from django.db import models class Book(models.Model):
title=models.CharField(max_length=32)
publishDate=models.DateField()
price=models.DecimalField(max_digits=5,decimal_places=2) # 出版社可以发布多部书(一对多)
publish=models.ForeignKey('Publish') # 一个人可以写多本书,一本书也可以由多个人撰写(多对多)
authorList=models.ManyToManyField('Author') class Author(models.Model):
name=models.CharField(max_length=32)
age=models.IntegerField()
addr=models.CharField(max_length=32)
tel=models.CharField(max_length=13) class Publish(models.Model):
name=models.CharField(max_length=32)
addr=models.CharField(max_length=32)
2 urls配置
from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^index/', views.index),
]
5 测试数据
作者数据
出版社数据
书籍数据
4 编写views代码
def index(request):
bookobj = models.Book.objects.all()
# 练习1: 查询人民出版社出版过的所有书籍的名字与价格(一对多)
# ret = models.Book.objects.filter(publish__name='山西出版社').values_list('title')
# ret = models.Publish.objects.filter(name='山西出版社').values_list('book__title','book__authorList__name')
# ret = models.Author.objects.filter(book__publish__name='山西出版社').values_list('book__title')
# 练习2: 查询egon出过的所有书籍的名字(多对多)
# ret = models.Book.objects.filter(authorList__name='alex').values_list('title')
# ret =models.Author.objects.filter(name='alex').values_list('book__title')
# 练习3: 查询人民出版社出版过的所有书籍的名字以及作者的姓名
# ret = models.Publish.objects.filter(name='机械先驱出版社').values_list('book__title','book__authorList__name')
# ret = models.Book.objects.filter(publish__name='机械先驱出版社').values_list('title','authorList__name')
# ret = models.Author.objects.filter(book__publish__name='机械先驱出版社').values_list('book__title','name')
# 练习4: 手机号以151开头的作者出版过的所有书籍名称以及出版社名称
# ret = models.Author.objects.filter(tel__startswith='158').values_list('book__title','book__publish__name')
# ret =models.Publish.objects.filter(book__authorList__tel__startswith='158').values_list('book__title','name')
# ret = models.Book.objects.filter(authorList__tel__startswith='158').values_list('publish__name','title')
# print(ret)
return HttpResponse('OK')