书籍
创建书籍表
# 书籍 class BOOES(models.Model): name = models.CharField(max_length=20, unique=True) pub = models.ForeignKey('Press', on_delete=models.CASCADE)
# Press :出版社表,默认关联主键,'Press':以反射的方式取得类,会自动添加_id ,比如:pub_id
# on_delete=models.CASCADE :级联删除,Django1.0 此参数为默认值,Django2.0 必填
数据库迁移
python manage.py makemigrations # 将models变更记录保存到migrations python manage.py migrate # 将变更同步到数据库中
在urls.py下添加url
# 展示书籍 url(r'^book/', views.book),
展示书籍在views.py中写入函数,没有优化
# 展示书籍 def book(request): # 获取书籍信息 all_book = models.Book.objects.all() # for book in all_book: # print(book) #对象 # print(book.pk) #ID # print(book.name) #字段 # print(book.pub) #取得的是书籍关联出版社的对象 # print(book.pub.name) #字段 # print(book.pub.pk) # print(book.pub_id) #与pub.name相同,推荐此方法 # print('*' * 20) return render(request, 'book.html', {"books": all_book})
添加书籍
# 添加书籍 url(r'^add_book/', views.add_book),
# 添加书籍 def add_book(request): if request.method == 'POST': # 获取提交的数据 new_name = request.POST.get('new_name') pub_id = request.POST.get('pub_id') # 插入到数据库中 # pub_obj = models.Publisher.objects.get(pk=pub_id) # models.Book.objects.create(name=new_name, pub=pub_obj) models.Book.objects.create(name=new_name, pub_id=pub_id) # 跳转到展示页面 return redirect('/book/') # 查询所有的出版社信息 all_pubs = models.Publisher.objects.all() return render(request, 'add_book.html', {'all_pubs': all_pubs})