Django ORM常用操作介紹 (初級)

圖片來源簡書

??Django開發(fā)過程中對表(model)的增刪改查是最常用的功能之一,本文介紹筆者在使用model 操作過程中遇到的一些操作。

1 model update常規(guī)用法

假如我們的表結(jié)構(gòu)是這樣的

class User(models.Model):
    username = models.CharField(max_length=255, unique=True, verbose_name='用戶名')
    is_active = models.BooleanField(default=False, verbose_name='激活狀態(tài)')

那么我們修改用戶名和狀態(tài)可以使用如下兩種方法:

方法一:

User.objects.filter(id=1).update(username='nick',is_active=True)

方法二:

_t = User.objects.get(id=1)
_t.username='nick'
_t.is_active=True
_t.save()

方法一適合更新一批數(shù)據(jù),類似于mysql語句 update user set username='nick' where id = 1

方法二適合更新一條數(shù)據(jù),也只能更新一條數(shù)據(jù),當(dāng)只有一條數(shù)據(jù)更新時推薦使用此方法,另外此方法還有一個好處,我們接著往下看

2 具有auto_now屬性字段的更新

我們通常會給表添加三個默認(rèn)字段

??自增ID,這個django已經(jīng)默認(rèn)加了,就像上邊的建表語句,雖然只寫了username和is_active兩個字段,但表建好后也會有一個默認(rèn)的自增id字段

??創(chuàng)建時間,用來標(biāo)識這條記錄的創(chuàng)建時間,具有auto_now_add屬性,創(chuàng)建記錄時會自動填充當(dāng)前時間到此字段

??修改時間,用來標(biāo)識這條記錄最后一次的修改時間,具有auto_now屬性,當(dāng)記錄發(fā)生變化時填充當(dāng)前時間到此字段

就像下邊這樣的表結(jié)構(gòu)

class User(models.Model):
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='創(chuàng)建時間')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新時間')
    username = models.CharField(max_length=255, unique=True, verbose_name='用戶名')
    is_active = models.BooleanField(default=False, verbose_name='激活狀態(tài)')

??當(dāng)表有字段具有auto_now屬性且你希望他能自動更新時,必須使用上邊方法二的更新,不然auto_now字段不會更新,也就是:

_t = User.objects.get(id=1)
_t.username='nick'
_t.is_active=True
_t.save()

3 json/dict類型數(shù)據(jù)更新字段

??目前主流的web開放方式都講究前后端分離,分離之后前后端交互的數(shù)據(jù)格式大都用通用的json型,那么如何用最少的代碼方便的更新json格式數(shù)據(jù)到數(shù)據(jù)庫呢?同樣可以使用如下兩種方法:

方法一:

data = {'username':'nick','is_active':'0'}
User.objects.filter(id=1).update(**data)
  • 同樣這種方法不能自動更新具有auto_now屬性字段的值

  • 通常我們再變量前加一個星號(*)表示這個變量是元組/列表,加兩個星號表示這個參數(shù)是字典

方法二:

data = {'username':'nick','is_active':'0'}
_t = User.objects.get(id=1)
_t.__dict__.update(**data)
_t.save()
  • 方法二和方法一同樣無法自動更新auto_now字段的值
  • 注意這里使用到了一個dict方法

方法三:

_t = User.objects.get(id=1)
_t.role=Role.objects.get(id=3)
_t.save()

4 ForeignKey字段更新

假如我們的表中有Foreignkey外鍵時,該如何更新呢?

class User(models.Model):
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='創(chuàng)建時間')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新時間')
    username = models.CharField(max_length=255, unique=True, verbose_name='用戶名')
    is_active = models.BooleanField(default=False, verbose_name='激活狀態(tài)')
    role = models.ForeignKey(Role, on_delete=models.CASCADE, null=True, verbose_name='角色')

方法一:

User.objects.filter(id=1).update(role=2)
  • 最簡單的方法,直接讓給role字段設(shè)置為一個id即可
  • 當(dāng)然也可以用dict作為參數(shù)更新:
User.objects.filter(id=1).update(**{'username':'nick','role':3})

方法二:

_role = Role.objects.get(id=2)
User.objects.filter(id=1).update(role=_role)
  • 也可以賦值一個實例給role
  • 當(dāng)然也可以用dict作為參數(shù)更新:
_role = Role.objects.get(id=1)
User.objects.filter(id=1).update(**{'username':'nick','role':_role})

方法三

_t = User.objects.get(id=1)
_t.role=Role.objects.get(id=3)
_t.save()
  • 注意:這里的role必須賦值為一個對象,不能寫id,不然會報錯"User.role" must be a "Role" instance
  • 當(dāng)使用dict作為參數(shù)更新時又有一點不同,如下代碼:
_t = User.objects.get(id=1)
_t.__dict__.update(**{'username':'nick','role_id':2})
_t.save()
  • Foreignkey外鍵必須加上_id,例如:{'role_id':3}
  • role_id后邊必須跟一個id(int或str類型都可),不能跟role實例

5 ManyToManyField字段更新

假如我們的表中有ManyToManyField字段時更新又有什么影響呢?

class User(models.Model):
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='創(chuàng)建時間')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新時間')
    username = models.CharField(max_length=255, unique=True, verbose_name='用戶名')
    is_active = models.BooleanField(default=False, verbose_name='激活狀態(tài)')
    role = models.ForeignKey(Role, on_delete=models.CASCADE, null=True, verbose_name='角色')
    groups = models.ManyToManyField(Group, null=True, verbose_name='組')

m2m更新:m2m字段沒有直接更新的方法,只能通過清空再添加的方法更新了

_t = User.objects.get(id=1)
_t.groups.clear()
_t.groups.add(*[1,3,5])
_t.save()
  • add():m2m字段添加一個值,當(dāng)有多個值的時候可用列表,參照上邊例子

_t.groups.add(2)

_t.groups.add(Group.objects.get(id=2))

  • remove():m2m字段移除一個值,,當(dāng)有多個值的時候可用列表,參照上邊例子

_t.groups.remove(2)

_t.groups.remove(Group.objects.get(id=2))

  • clear():清空m2m字段的值

6 Django model select的各種用法詳解

? 基本操作

# 獲取所有數(shù)據(jù),對應(yīng)SQL:select * from User
User.objects.all()

# 匹配,對應(yīng)SQL:select * from User where name = '運(yùn)維咖啡吧'
User.objects.filter(name='運(yùn)維咖啡吧')

# 不匹配,對應(yīng)SQL:select * from User where name != '運(yùn)維咖啡吧'
User.objects.exclude(name='運(yùn)維咖啡吧')

# 獲取單條數(shù)據(jù)(有且僅有一條,id唯一),對應(yīng)SQL:select * from User where id = 724
User.objects.get(id=123)

? 常用操作

# 獲取總數(shù),對應(yīng)SQL:select count(1) from User
User.objects.count()

# 獲取總數(shù),對應(yīng)SQL:select count(1) from User where name = '運(yùn)維咖啡吧'
User.objects.filter(name='運(yùn)維咖啡吧').count()

# 大于,>,對應(yīng)SQL:select * from User where id > 724
User.objects.filter(id__gt=724)

# 大于等于,>=,對應(yīng)SQL:select * from User where id >= 724
User.objects.filter(id__gte=724)

# 小于,<,對應(yīng)SQL:select * from User where id < 724
User.objects.filter(id__lt=724)

# 小于等于,<=,對應(yīng)SQL:select * from User where id <= 724
User.objects.filter(id__lte=724)

# 同時大于和小于, 1 < id < 10,對應(yīng)SQL:select * from User where id > 1 and id < 10
User.objects.filter(id__gt=1, id__lt=10)

# 包含,in,對應(yīng)SQL:select * from User where id in (11,22,33)
User.objects.filter(id__in=[11, 22, 33])

# 不包含,not in,對應(yīng)SQL:select * from User where id not in (11,22,33)
User.objects.exclude(id__in=[11, 22, 33])

# 為空:isnull=True,對應(yīng)SQL:select * from User where pub_date is null
User.objects.filter(pub_date__isnull=True)

# 不為空:isnull=False,對應(yīng)SQL:select * from User where pub_date is not null
User.objects.filter(pub_date__isnull=True)

# 匹配,like,大小寫敏感,對應(yīng)SQL:select * from User where name like '%sre%',SQL中大小寫不敏感
User.objects.filter(name__contains="sre")

# 匹配,like,大小寫不敏感,對應(yīng)SQL:select * from User where name like '%sre%',SQL中大小寫不敏感
User.objects.filter(name__icontains="sre")

# 不匹配,大小寫敏感,對應(yīng)SQL:select * from User where name not like '%sre%',SQL中大小寫不敏感
User.objects.exclude(name__contains="sre")

# 不匹配,大小寫不敏感,對應(yīng)SQL:select * from User where name not like '%sre%',SQL中大小寫不敏感
User.objects.exclude(name__icontains="sre")

# 范圍,between and,對應(yīng)SQL:select * from User where id between 3 and 8
User.objects.filter(id__range=[3, 8])

# 以什么開頭,大小寫敏感,對應(yīng)SQL:select * from User where name like 'sh%',SQL中大小寫不敏感
User.objects.filter(name__startswith='sre')

# 以什么開頭,大小寫不敏感,對應(yīng)SQL:select * from User where name like 'sh%',SQL中大小寫不敏感
User.objects.filter(name__istartswith='sre')

# 以什么結(jié)尾,大小寫敏感,對應(yīng)SQL:select * from User where name like '%sre',SQL中大小寫不敏感
User.objects.filter(name__endswith='sre')

# 以什么結(jié)尾,大小寫不敏感,對應(yīng)SQL:select * from User where name like '%sre',SQL中大小寫不敏感
User.objects.filter(name__iendswith='sre')

# 排序,order by,正序,對應(yīng)SQL:select * from User where name = '運(yùn)維咖啡吧' order by id
User.objects.filter(name='運(yùn)維咖啡吧').order_by('id')

# 多級排序,order by,先按name進(jìn)行正序排列,如果name一致則再按照id倒敘排列
User.objects.filter(name='運(yùn)維咖啡吧').order_by('name','-id')

# 排序,order by,倒序,對應(yīng)SQL:select * from User where name = '運(yùn)維咖啡吧' order by id desc
User.objects.filter(name='運(yùn)維咖啡吧').order_by('-id')

? 進(jìn)階操作

# limit,對應(yīng)SQL:select * from User limit 3;
User.objects.all()[:3]

# limit,取第三條以后的數(shù)據(jù),沒有對應(yīng)的SQL,類似的如:select * from User limit 3,10000000,從第3條開始取數(shù)據(jù),取10000000條(10000000大于表中數(shù)據(jù)條數(shù))
User.objects.all()[3:]

# offset,取出結(jié)果的第10-20條數(shù)據(jù)(不包含10,包含20),也沒有對應(yīng)SQL,參考上邊的SQL寫法
User.objects.all()[10:20]

# 分組,group by,對應(yīng)SQL:select username,count(1) from User group by username;
from django.db.models import Count
User.objects.values_list('username').annotate(Count('id'))

# 去重distinct,對應(yīng)SQL:select distinct(username) from User
User.objects.values('username').distinct().count()

# filter多列、查詢多列,對應(yīng)SQL:select username,fullname from accounts_user
User.objects.values_list('username', 'fullname')

# filter單列、查詢單列,正常values_list給出的結(jié)果是個列表,里邊里邊的每條數(shù)據(jù)對應(yīng)一個元組,當(dāng)只查詢一列時,可以使用flat標(biāo)簽去掉元組,將每條數(shù)據(jù)的結(jié)果以字符串的形式存儲在列表中,從而避免解析元組的麻煩
User.objects.values_list('username', flat=True)

# int字段取最大值、最小值、綜合、平均數(shù)
from django.db.models import Sum,Count,Max,Min,Avg

User.objects.aggregate(Count(‘id’))
User.objects.aggregate(Sum(‘a(chǎn)ge’))

? 時間字段

# 匹配日期,date
User.objects.filter(create_time__date=datetime.date(2018, 8, 1))
User.objects.filter(create_time__date__gt=datetime.date(2018, 8, 2))

# 匹配年,year
User.objects.filter(create_time__year=2018)
User.objects.filter(create_time__year__gte=2018)

# 匹配月,month
User.objects.filter(create_time__month__gt=7)
User.objects.filter(create_time__month__gte=7)

# 匹配日,day
User.objects.filter(create_time__day=8)
User.objects.filter(create_time__day__gte=8)

# 匹配周,week_day
 User.objects.filter(create_time__week_day=2)
User.objects.filter(create_time__week_day__gte=2)

# 匹配時,hour
User.objects.filter(create_time__hour=9)
User.objects.filter(create_time__hour__gte=9)

# 匹配分,minute
User.objects.filter(create_time__minute=15)
User.objects.filter(create_time__minute_gt=15)

# 匹配秒,second
User.objects.filter(create_time__second=15)
User.objects.filter(create_time__second__gte=15)


# 按天統(tǒng)計歸檔
today = datetime.date.today()
select = {'day': connection.ops.date_trunc_sql('day', 'create_time')}
deploy_date_count = Task.objects.filter(
    create_time__range=(today - datetime.timedelta(days=7), today)
).extra(select=select).values('day').annotate(number=Count('id'))

? Q 的使用

??Q對象可以對關(guān)鍵字參數(shù)進(jìn)行封裝,從而更好的應(yīng)用多個查詢,可以組合&(and)、|(or)、~(not)操作符。

例如下邊的語句

from django.db.models import Q

User.objects.filter(
    Q(role__startswith='sre_'),
    Q(name='公眾號') | Q(name='運(yùn)維咖啡吧')
)

轉(zhuǎn)換成SQL語句如下:

select * from User where role like 'sre_%' and (name='公眾號' or name='運(yùn)維咖啡吧')

??通常更多的時候我們用Q來做搜索邏輯,比如前臺搜索框輸入一個字符,后臺去數(shù)據(jù)庫中檢索標(biāo)題或內(nèi)容中是否包含

_s = request.GET.get('search')

_t = Blog.objects.all()
if _s:
    _t = _t.filter(
        Q(title__icontains=_s) |
        Q(content__icontains=_s)
    )

return _t

? 外鍵:ForeignKey

表結(jié)構(gòu):

class Role(models.Model):
    name = models.CharField(max_length=16, unique=True)


class User(models.Model):
    username = models.EmailField(max_length=255, unique=True)
    role = models.ForeignKey(Role, on_delete=models.CASCADE)
  • 正向查詢:
# 查詢用戶的角色名
_t = User.objects.get(username='運(yùn)維咖啡吧')
_t.role.name
  • 反向查詢:
# 查詢角色下包含的所有用戶
_t = Role.objects.get(name='Role03')
_t.user_set.all()
  • 另一種反向查詢的方法:
_t = Role.objects.get(name='Role03')

# 這種方法比上一種_set的方法查詢速度要快
User.objects.filter(role=_t)
  • 第三種反向查詢的方法:

如果外鍵字段有related_name屬性,例如models如下:

class User(models.Model):
    username = models.EmailField(max_length=255, unique=True)
    role = models.ForeignKey(Role, on_delete=models.CASCADE,related_name='roleUsers')

那么可以直接用related_name屬性取到某角色的所有用戶

_t = Role.objects.get(name = 'Role03')
_t.roleUsers.all()

? M2M:ManyToManyField

表結(jié)構(gòu):

class Group(models.Model):
    name = models.CharField(max_length=16, unique=True)

class User(models.Model):
    username = models.CharField(max_length=255, unique=True)
    groups = models.ManyToManyField(Group, related_name='groupUsers')
  • 正向查詢:
# 查詢用戶隸屬組
_t = User.objects.get(username = '運(yùn)維咖啡吧')
_t.groups.all()
  • 反向查詢:
# 查詢組包含用戶
_t = Group.objects.get(name = 'groupC')
_t.user_set.all()

同樣M2M字段如果有related_name屬性,那么可以直接用下邊的方式反查

_t = Group.objects.get(name = 'groupC')
_t.groupUsers.all()
get_object_o

? get_or_create

顧名思義,查找一個對象如果不存在則創(chuàng)建,如下:

object, created = User.objects.get_or_create(username='運(yùn)維咖啡吧')

返回一個由object和created組成的元組,其中object就是一個查詢到的或者是被創(chuàng)建的對象,created是一個表示是否創(chuàng)建了新對象的布爾值

實現(xiàn)方式類似于下邊這樣:

try:
    object = User.objects.get(username='運(yùn)維咖啡吧')

    created = False
exception User.DoesNoExist:
    object = User(username='運(yùn)維咖啡吧')
    object.save()

    created = True

returen object, created

? 執(zhí)行原生SQL

??Django中能用ORM的就用它ORM吧,不建議執(zhí)行原生SQL,可能會有一些安全問題,如果實在是SQL太復(fù)雜ORM實現(xiàn)不了,那就看看下邊執(zhí)行原生SQL的方法,跟直接使用pymysql基本一致了

from django.db import connection

with connection.cursor() as cursor:
    cursor.execute('select * from accounts_User')
    row = cursor.fetchall()

return row

注意這里表名字要用app名+下劃線+model名的方式

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容