Django之QuerySet 创建对象

在前面的模型介绍中设置了3个对象,出版商(publisher),作者(Authro),书籍(book)。首先我们在网页中添加各个对象信息填写的界面。填写后点击提交。将会传递给后端。传递方式采用post

后端生出处理代码如下:

def show_all_infor(request):
if request.method == 'POST':
publish=request.POST['pubisher']
address=request.POST['address']
city=request.POST['city']
state_province=request.POST['state_province']
coutry=request.POST['coutry']
web=request.POST['web']
ret1=Publisher.objects.get_or_create(name=publish,address=address,city=city,state_province=state_province,country=coutry,website=web)
firstname=request.POST['firstname']
secondname=request.POST['secondname']
email=request.POST['email']
ret2=Author.objects.get_or_create(first_name=firstname,last_name=secondname,email=email)
title=unicode(request.POST['title'])
publish_date=unicode(request.POST['publish_date'])
if len(Book.objects.filter(title=title)) > 0:
return HttpResponse('already exist')
else:
ret3=Book()
ret3.title=title
ret3.publisher=Publisher.objects.all()[1]
ret3.publish_date=publish_date
ret3.save()
ret3.authors.add(Author.objects.all()[1])
return HttpResponse(Book.objects.all())

首先判断数据传递方式是否是post. 如果是的话则取出post的数据。然后进行对象创建。在这里用的是Publisher.objects.get_or_create方法。其实对象创建总共有4种方法:

方法一:

Publisher.objects.create(name=publish,address=address,city=city,state_province=state_provicen,coutry=coutry,website=web)

方法二:

ret=Publisher(name=publish,address=address,city=city,state_province=state_provicen,coutry=coutry,website=web)

ret.save()

方法三:

ret=Publisher()

ret.name=publish

ret.address=address

ret.save()

方法四:首先尝试获取。不存在就创建,可以防止重复。就是这里采取的方法。

ret1=Publisher.objects.get_or_create(name=publish,address=address,city=city,state_province=state_province,country=coutry,website=web)

 

Publisher和Author创建的方法都是get_or_create的方法,这里需要重点讲下Book的创建方法。在Book中有个字段authors和publisher分别是ManyToManyField和ForeignKey

authors=models.ManyToManyField(Author)
publisher=models.ForeignKey(Publisher)
 
首先来看下publisher的创建。由于是ForeignKey的关系,也就是一对多。因此直接从Publisher对象中选择一个进行赋值就可以了
ret3.publisher=Publisher.objects.all()[1]
 
接下来看下authors的创建,authors是ManyToManyField,也就是多对多的关系。在创建的authors的时候要注意两点:
1 首先是要创建一个Book对象,然后进行保存。才能进行添加authors。如果代码是这样的:
ret3=Book()
ret3.authors.add(Author.objects.all()[1])
ret3.title=title
ret3.publisher=Publisher.objects.all()[1]
ret3.publish_date=publish_date
ret3.save()
则会报如下的错误"<Book: >" needs to have a value for field "book" before this many-to-many relationship can be used.
这个错误的意思就是需要先创建一个book的对象

因此正确的代码就是:
ret3=Book()
ret3.title=title
ret3.publisher=Publisher.objects.all()[1]
ret3.publish_date=publish_date
ret3.save()
ret3.authors.add(Author.objects.all()[1])
 
2 在创建Book对象的时候需要将书名,出版商,出版日期都包含进来,否则会报错。
如果代码是下面的这样:
ret3=Book()
ret3.save()
ret3.title=title
ret3.publisher=Publisher.objects.all()[1]
ret3.publish_date=publish_date
ret3.authors.add(Author.objects.all()[1])
就会报如下的错误IntegrityError:site_prj_book.publisher_id may not be NULL

因此正确的代码如下:
ret3=Book()
ret3.title=title
ret3.publisher=Publisher.objects.all()[1]
ret3.publish_date=publish_date
ret3.save()
ret3.authors.add(Author.objects.all()[1])
 

另外在创建Book对象的时候,并没有用到get_or_create的方法。这是因为Book有ManyToManyField和ForeignKey的关系,需要首先创建一个对象。但是存在一个问题,如果输入的书名已经有记录了,那么如何避免重复记录呢,这里用到了filter方法:

Book.objects.filter(title=title)
过滤该名字的书名,如果存在,则返回already exist的界面。就不会继续新建对象。
if len(Book.objects.filter(title=title)) > 0:
   return HttpResponse('already exist')
 
来看下几个查询界面的后端处理代码:首先是获取所有的对象。然后在网页上显示
def result1(request):
result=Publisher.objects.all()
return HttpResponse(result)

def result2(request):
result=Author.objects.all()
return HttpResponse(result)

def result3(request):
result=Book.objects.all()
return HttpResponse(result)
其实相对于在网页上显示,在Django工程中也有查询的方法。在pycharm中进入终端,然后输入python manage.py shell进入管理界面。
D:\django_test2>python manage.py shell
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
 
IPython 5.3.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
然后从模型中引入各个模块
In [1]: from site_prj.models import Publisher,Author,Book
 
输入查询语句:
In [2]: Publisher.objects.all()
得到结果:

Out[2]: <QuerySet [<Publisher: 成都日报>

 

另外我们还可以在shell中打印出对应的SQL语句便于问题定位和查看:

In [5]: print Publisher.objects.all().query

SELECT "site_prj_publisher"."id", "site_prj_publisher"."name", "site_prj_publisher"."address", "site_prj_publisher"."city", "site_prj_publisher"."state_province", "site_prj_publisher"."country", "site_prj_publishe

r"."website" FROM "site_prj_publisher"

 

这一章介绍了对象创建的基本方法,下一章将介绍更对对象的高级应用。

 


 


posted @ 2017-11-20 15:17  red_leaf_412  阅读(3703)  评论(0编辑  收藏  举报