在前面的模型介紹中設置了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"
這一章介紹了對象創建的基本方法,下一章將介紹更對對象的高級應用。
