單表
表結構
常用字段類型
字段 |
備註 |
AutoField |
自增列, 必須填入 primary_key=True, 如果沒有該列, 會自動創建一個名爲 id 的列 |
IntegerField |
10 位內數字 |
CharField |
字符串類型, 必須填如 manx_length 參數限制長度 |
DateField |
YYYY-MM-DD, 相當於 datetime.date() |
DateTimeField |
YYYY-MM-DD HH:MM:[:ss:[.uuuuuu]], 相當於 datetime.datetime() |
常用參數
參數 |
註釋 |
null |
是否允許爲空 |
unique |
是否唯一 |
db_index |
設置爲索引 |
default |
設置默認值 |
auto_now_add=True |
記錄創建時間 |
auto_now=True |
記錄變更時間 |
創建
class Person(models.Model):
name = models.CharField(max_length=16)
age = models.IntegerField(default=18)
phone = models.CharField(max_length=11, unique=True)
數據的增刪改查
增
models.Publisher.objects.create(name="Gury", age=19, phone="1231231234")
基礎查詢
models.Person.objects.all()
models.Person.objects.filter(id=1)
models.Person.objects.get(id=1)
models.Person.objects.filter(age=16).values("name", "phone")
models.Person.objects.filter(age=16).values_list("name", "phone")
models.Person.objects.exclude(id=1)
models.Person.objects.all().order_by("id")
models.Person.objects.all().order_by("id").reverse()
distinct()
count()
first()
last()
exists()
進階查詢(雙下劃線用法)
models.Person.objects.filter(id__gt=1)
models.Person.objects.filter(id__lt=2)
models.Person.objects.filter(id__gte=1)
models.Person.objects.filter(id__lte=2)
models.Person.objects.filter(id__in=[1,3])
models.Person.objects.exclude(id__in=[1,2])
models.Person.objects.filter(name__contains="t")
models.Person.objects.filter(name__icontains="T")
models.Person.objects.filter(id__range=[1,4])
models.Person.objects.filter(name__startswith="t")
models.Person.objects.filter(birthday__year=2018)
編輯
obj = models.Person.objects.get(id=1)
obj.name = "new_name"
obj.save()
刪
models.Publisher.objects.get(id=1).delete()
一對多外鍵
表結構的創建
class Person(models.Model):
name = models.CharField(max_length=16)
age = models.IntegerField(default=18)
phone = models.CharField(max_length=11, unique=True)
class Book(models.Model):
title = models.CharField(max_length=32)
author = models.ForeignKey(to="Person", on_delete=models.CASCADE)
查詢用法
"""
一個人可以寫多本書
"一"對應作者
"多"對應書籍
"""
book_obj = models.Book.objects.first()
book_obj.author.name
models.Book.objects.all().values_list("author__name")
author_obj = models.Person.objects.first()
author_obj.book_set.all()
models.Person.objects.filter(id=1).values_list("book__title")