Model | 數據庫操作 |
Form | 用戶請求的驗證 |
ModelForm | 數據庫操作(部分)用戶請求驗證(部分) |
Model操作
數據表操作
- Code First(代碼優先)
- 創建類 -> 自動生成表
- DB First(數據庫有限)
- 創建表 -> 自動生成類
類
一對多操作
# 用戶表
class User(models.Model):
name = models.CharField(max_length=10)
email = models.EmailField(max_length=32)
# 與用戶類型表建立一對多關係
user_type = models.ForeignKey('UserType')
# 用戶類型表
class UserType(mdoels.Model):
name = models.CharField(max_length=10)
應用場景:
建立多對多操作的兩種方式
- django的ManyToManyField()
更適合admin添加表數據
- 自己創建第三張表以兩個ForeignKey()建立多對多關係
更適合調用表數據
一對一(OneToOneField())表
應用場景:1.單表過大,2.適合admin選擇一對一數據
字段
數字
字符串
user = models.CharField() # 普通字符
email = models.EmailField() # 帶正則的字符串
時間
二進制
文件
fiel = models.FileField(upload_to='path') # 文件
#圖像
w = models.IntegerField() # 寬度
h = models.IntegerField() # 高度
img = ImageField(upload_to='path', width_field='w', height_field='h') # 自動獲取圖片寬高
字段參數
"""指定生成數據庫列信息"""
null 數據庫中字段是否可以爲空
db_column 數據庫中字段的列名
default 數據庫中字段的默認值
primary_key 數據庫中字段是否爲主鍵
db_index 數據庫中字段是否可以建立索引
unique 數據庫中字段是否可以建立唯一索引
unique_for_date 數據庫中字段【日期】部分是否可以建立唯一索引
unique_for_month 數據庫中字段【月】部分是否可以建立唯一索引
unique_for_year 數據庫中字段【年】部分是否可以建立唯一索引
"""外鍵字段參數"""
to
to_fields
related_name
on_delete
limit_choices_to
"""admin顯示信息"""
verbose_name Admin中顯示的字段名稱
blank Admin中是否允許用戶輸入爲空
editable Admin中是否可以編輯
help_text Admin中該字段的提示信息
choices Admin中顯示選擇框的內容,用不變動的數據放在內存中從而避免跨表操作
如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1)
"""驗證信息"""
error_messages 自定義錯誤信息(字典類型),從而定製想要顯示的錯誤信息;
字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date
如:{'null': "不能爲空.", 'invalid': '格式錯誤'}
validators 自定義錯誤驗證(列表類型),從而定製想要的驗證規則
from django.core.validators import RegexValidator
from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\
MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
# 如:
test = models.CharField(
max_length=32,
error_messages={
'c1': '優先錯信息1',
'c2': '優先錯信息2',
'c3': '優先錯信息3',
},
validators=[
RegexValidator(regex='root_\d+', message='錯誤了', code='c1'),
RegexValidator(regex='root_112233\d+', message='又錯誤了', code='c2'),
EmailValidator(message='又錯誤了', code='c3'), ]
)
數據行操作
create
delete
all
get
filter
exclude
filter(xx__in=[])
filter(xx__gte=[])
filter(xx__lte=[])
filter(xx__range=[])
filter(xx__contains=[])
filter(xx__icontains=[])
filter(xx__regex=[])
filter(xx_isnull)
filter(xx__in=[])[1:10]
only
defer
first
last
reverse
Q
F
get_or_create
update_or_create
in_bulk
extra
using
dates
exists
values
values_list
aggregate
raw
connections
update
add
set
remove
save
select_related
prefetch_related
count
distinct
order_by
group_by
annotate
none
Form
生成html,並附加強大的數據驗證
<!-- html中 -->
調用後端傳過來的form表單
{{ obj.as_p }}
{{ obj.as_ul }}
<table>
{{ obj.as_table }}
</table>
# 後端驗證
def index(request):
if request.method == 'GET':
obj = UserForm()
render(request, 'index.html')
elif request.method == 'POST':
obj = UserForm(request.POST)
obj.is_valid() # 驗證結果True|False
# obj.clean() # 符合規則的數據
obj.cleaned_data # 如果自定義了clean方法,使用cleaned_data獲取錯誤信息
obj.errors() # 錯誤信息
render(request, 'index.html)
form函數
from django import forms
from django.forms import field
from django.core.exceptions import ValidationError
# 創建用戶表單
class UserForm(forms.Form):
# 創建字段用戶名
username = fields.CharField(label='用戶名')
email = fields.EmailField(label='郵箱')
# 自定義驗證方法
def clean_username(self):
"""
驗證user字段數據
:return: 拋出異常或滿足條件的值或自定義值
"""
# 獲取用戶輸入數據
username_input = self.cleaned_data['username']
if 條件:
return username_input
else:
raise ValidationError('錯誤信息')
# 1. 重寫clean方法,自定義錯誤信息(*)
def clean(self):
"""
多項數據組合驗證
:return: 拋出異常,或返回self.cleaned_data
"""
username = self.cleaned_data['username']
email = self.cleaned_data['email']
if username == 'root' and email == '[email protected]':
return self.cleaned_data
else:
raise ValidationError('錯誤信息')
"""
但是因爲重寫了clean()方法,在views.py中,如果使用obj.clean()獲取正確數據會拋出錯誤,我們要使用obj.cleaned_data獲取所有輸入的信息
"""
# 2. 純粹自定義數據處理
def _post_clean(self):
"""
這裏不允許報錯,沒有返回值,如果沒滿足條件,就添加錯誤信息
:return:
"""
try:
username_input = self.cleaned_data['user']
email_input = self.cleaned_data['email']
if username_input == 'wolf' and email_input == '[email protected]':
pass
except:
self.add_error('__all__', ValidationError('用戶名或郵箱錯誤', code='error-info'))
models中也有full_clean()方法,不過需要自己處理異常
def full_clean(self):
try:
...
except:
...
ModelForm
有model和form的功能:實時更新choices數據,保存正確格式的輸入信息,對於多對多表,同時保存三張表的數據
Model中
定義
from django import forms
class UserModelForm(forms.ModelForm):
class Meta:
model = models.User
fields = '__all__'
操作
def index(request):
if request.method == 'POST':
# 數據庫對象
obj = models.User.objects.filter(id=1)
# 保存數據
obj = UserModelForm(request.POST, request.FILES)
obj.save()
# 對上面的對象修改
form_obj = UserModelForm(request.POST, instance=obj)
obj.save()
# 等價於下面三句
# instance = obj.save(commit=False) # 修改表本身數據
# instance.save()
# obj.save_m2mName() # 修改關聯表數據
Form中
定義
操作
obj = forms.UserModelForm(request.POST, request.FILES)
obj.is_valid()
obj.clean()
obj.errors()
modelform中
from django import forms
class UserModelForm(forms.ModelForm):
class Meta:
# 取user的字段
model = models.User
# 對應所有字段
fields = '__all__'
ModelForm的Meta配置參數
from django.forms import widgets as wgt
class UserModelForm(forms.ModelForm):
class Meta:
model = models.User
fields = '__all__'
# fields = ['name', 'user_type']
exclude = ['name'] # 排除name
labels = {
'email': '郵箱',
'username': '用戶名'
} # 批量修改label
help_texts = {
'email': '*',
} # 在對應的輸入框後面添加幫助信息
widgets = {
'name': wgt.Textarea(attr={'class': 'c1'})
} # 設置窗口插件
error_message = {
'name': {'require': '不能爲空', 'invalid': '格式錯誤'},
} # 設置錯誤信息
field_classes = {
'name': forms.EmailField
} # 按form中的規則做驗證
localized_fields = ('ctime', ) # 本地化:某字段以本地時間顯示