model的常用字段
V=models.CharField(max_length=None[, **options]) #varchar
V=models.EmailField([max_length=75, **options]) #varchar
V=models.URLField([verify_exists=True, max_length=200, **options]) #varchar
V=models.FileField(upload_to=None[, max_length=100, **options]) #varchar
#upload_to指定保存目錄可帶格式,
V=models.ImageField(upload_to=None[, height_field=None, width_field=None, max_length=100, **options])
V=models.IPAddressField([**options]) #varchar
V=models.FilePathField(path=None[, match=None, recursive=False, max_length=100, **options]) #varchar
V=models.SlugField([max_length=50, **options]) #varchar,標籤,內含索引
V=models.CommaSeparatedIntegerField(max_length=None[, **options]) #varchar
V=models.IntegerField([**options]) #int
V=models.PositiveIntegerField([**options]) #int 正整數
V=models.SmallIntegerField([**options]) #smallint
V=models.PositiveSmallIntegerField([**options]) #smallint 正整數
V=models.AutoField(**options) #int;在Django代碼內是自增
V=models.DecimalField(max_digits=None, decimal_places=None[, **options]) #decimal
V=models.FloatField([**options]) #real
V=models.BooleanField(**options) #boolean或bit
V=models.NullBooleanField([**options]) #bit字段上可以設置上null值
V=models.DateField([auto_now=False, auto_now_add=False, **options]) #date
#auto_now最後修改記錄的日期;auto_now_add添加記錄的日期
V=models.DateTimeField([auto_now=False, auto_now_add=False, **options]) #datetime
V=models.TimeField([auto_now=False, auto_now_add=False, **options]) #time
V=models.TextField([**options]) #text
V=models.XMLField(schema_path=None[, **options]) #text
——————————————————————————–
V=models.ForeignKey(othermodel[, **options]) #外鍵,關聯其它模型,創建關聯索引
V=models.ManyToManyField(othermodel[, **options]) #多對多,關聯其它模型,創建關聯表
V=models.OneToOneField(othermodel[, parent_link=False, **options]) #一對一,字段關聯表屬性
經典情景示例
書籍,作者,出版社之間的關係,這裏爲了便於演示,我們儘量精簡了表中的字段,書籍表具有書名,出版社同出版社表建立一對多的關係[foreign key],一本書可以具有多個作者,又同作者表建立多對多的關係[many-to-many],作者表有名稱,年齡,出版社表有出版社名稱。
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher,on_delete=models.CASCADE)
def __str__(self):
return self.title
選擇對象
- 獲取全體對象
Publisher.objects.all() #獲取所有對象
- 篩選對象
Publisher.objects.filter(name='人們教育出版社') #獲取的是一個對象列表
dict = {'name':'lemon','age':18}
Author.objects.filter(**dict) #列表傳參的方法
- 獲取單個對象
Publisher.objects.get(name='機械工業出版社') #找不到會報錯!!!
- 對象排序
Author.objects.order_by("name","-age") #可以按照多個字段排序,- 表示逆向排序
- 連查
Author.objects.filter(name='lemon').order_by('-age')[0]
- 批量更新
Author.objects.all().update(age='18')
- 刪除對象
Author.objects.filter(name='lemon').delete()
外鍵和多對多操作
- 訪問外鍵
Book.objects.get(id=1).publisher #得到書籍的出版社
- 反向查詢
models.Publisher.objects.get(id=1).book_set.all() #反向查詢,得到的是一個queryset對象列表
- 多對多操作
Book.objects.get(id=1).authors.all() #得到queryset對象列表
自定義models方法
class Author(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
def __str__(self):
return self.name
def status(self):
if self.name=='lemon':
return '帥哥'
運行結果:
aa = models.Author.objects.get(id=1)
print(aa.status())
———————————————運行結果——————————————————
帥哥
自定義manager管理器
class AuthorManager(models.Manager):
def name_count(self,str_name):
return self.filter(name__icontains=str_name).count()
class Author(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
def __str__(self):
return self.name
def status(self):
if self.name=='lemon':
return '帥哥'
#一旦定義了新的管理器,默認管理器需要顯示聲明出來纔可以使用
objects = models.Manger() #默認管理器
object=AuthorManager() #新定義管理器
執行結果:
aa = models.Author.object.name_count('lemon')
print(aa) #——————》2
自定義sql語句
class AuthorManager(models.Manager):
def age_stat(self, age_int):
cursor = connection.cursor()
cursor.execute("""
SELECT NAME
FROM app2_author
WHERE age = %s""", [age_int])
#fetchall()返回的是元組的列表
return [row[0] for row in cursor.fetchall()]
class Author(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
# objects =models.Manager()
object=AuthorManager()
def __str__(self):
return self.name
執行結果:
aa = models.Author.object.age_stat(18)
print(aa)
-----------------
['lemon', 'Luouo']
過濾字段發方法
__exact 精確等於 like 'aaa'
__iexact 精確等於 忽略大小寫 ilike 'aaa'
__contains 包含 like '%aaa%'
__icontains 包含 忽略大小寫 ilike '%aaa%',但是對於sqlite來說,contains的作用效果等同於icontains。
__gt 大於
__gte 大於等於
__lt 小於
__lte 小於等於
__in 存在於一個list範圍內
__startswith 以...開頭
__istartswith 以...開頭 忽略大小寫
__endswith 以...結尾
__iendswith 以...結尾,忽略大小寫
__range 在...範圍內
__year 日期字段的年份
__month 日期字段的月份
__day 日期字段的日
__isnull=True/False