Django的學習筆記(三)(Django多對多關係模型)
阿新 • • 發佈:2018-12-30
第一節課:Django 定義模型
使用流程:
1.配置settings.py中的DATABASES
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #MySQL資料庫
'NAME': 'imooc', #資料庫名稱
'USER':'root', #使用者名稱
'PASSWORD':'root', #密碼
'HOST':'', #主機,預設本機
'PORT':'', #埠:預設3306
}
}
2.在models.py中編寫相關的類
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Employee(models.Model):
name = models.CharField(max_length=20)
注:這表示會在資料庫中建立一個employee的表,且表中有一個name的欄位
3.同步資料庫
(1).右鍵專案–>Django–>Make Migrations–>輸入app的名稱:如blog:該步驟的用處是在blog下生成相應的migrations包
(2)右鍵專案–>Django–>Migrate:該步驟的作用是同步模型到資料庫上
控制檯輸出:
Operations to perform:
Apply all migrations: admin, blog, contenttypes, auth, sessions
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying blog.0001_initial... OK
Applying sessions.0001_initial... OK
Finished "F:\Python\Projects\cstv01\manage.py migrate" execution.
最終生成的專案結構和表結構
第二節課–>Django 模型資料操作
1.增加:三種增加記錄的方法
def add1(req,name):
employee = Employee()
employee.name = name
employee.save()
return HttpResponse("add1 success:",name)
def add2(req,name):
employee = Employee(name=name)
employee.save()
return HttpResponse("add2 success:",name)
def add3(req,name):
Employee.objects.create(name = name)
return HttpResponse("add2 success:",name)
2.查詢所有的記錄
def list(req):
employeeList = Employee.objects.all()
return render_to_response('list.html',{'emps':employeeList})
第三節課–>多對多模型
1.models.py檔案
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Author(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=30)
authors = models.ManyToManyField(Author)
def __unicode__(self):
return self.name
2.使用程式碼:
alen = Author.objects.create(name='Alen')
ben = Author.objects.create(name='Ben')
book = Book(name='python')
book.authors.add(alen)
book.authors.add(ben)
book.save()
#顯示效果
>>> book.authors.all()
[<Author: Alen>,<Author: Ben>]
>>>book.authors.remove(alen)#可以將Alen刪除
[<Author: Ben>]
>>> alen.book_set.all()
[<Book: python>]