最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django ORM實(shí)現(xiàn)按天獲取數(shù)據(jù)去重求和例子

 更新時(shí)間:2020年05月18日 09:59:55   作者:chenlunju  
這篇文章主要介紹了Django ORM實(shí)現(xiàn)按天獲取數(shù)據(jù)去重求和例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

我就廢話不多說(shuō)了,大家還是直接看代碼吧!

def total_data(request):
  data = request_body(request, 'POST')
  if not data:
    return http_return(400, '參數(shù)錯(cuò)誤')
  # 前端傳入毫秒為單位的時(shí)間戳
  startTimestamp = data.get('startTime', '')
  endTimestamp = data.get('endTime', '')

  if startTimestamp and endTimestamp:
    startTimestamp = int(startTimestamp/1000)
    endTimestamp = int(endTimestamp/1000)
  else:
    return http_return(400, '參數(shù)有誤')
  # 小于2019-05-30 00:00:00的時(shí)間不合法
  if endTimestamp < startTimestamp or endTimestamp <= 1559145600 or startTimestamp <= 1559145600:
    return http_return(400, '無(wú)效時(shí)間')
  if startTimestamp and endTimestamp:
    # 給定時(shí)間查詢
    startTime = datetime.fromtimestamp(startTimestamp)
    endTime = datetime.fromtimestamp(endTimestamp)
    t1 = datetime(startTime.year, startTime.month, startTime.day)
    t2 = datetime(endTime.year, endTime.month, endTime.day, 23, 59, 59, 999999)
    # 用戶總?cè)藬?shù)
    totalUsers = User.objects.exclude(status='destroy').count()
    # 音頻總數(shù)
    totalAudioStory = AudioStory.objects.filter(isDelete=False).count()
    # 專輯總數(shù)
    totalAlbums = Album.objects.filter(isDelete=False).count()
    # 新增用戶人數(shù)
    newUsers = User.objects.filter(createTime__range=(t1, t2)).exclude(status='destroy').count()
    # 活躍用戶人數(shù)
    activityUsers = LoginLog.objects.filter(createTime__range=(t1, t2), isManager=False).values('userUuid_id').\
      annotate(Count('userUuid_id')).count()
    # 新增音頻數(shù)
    newAudioStory = AudioStory.objects.filter(createTime__range=(t1, t2)).count()

    # 男性
    male = User.objects.filter(gender=1).exclude(status='destroy').count()

    # 女性
    female = User.objects.filter(gender=2).exclude(status='destroy').count()

    # 未知
    unkonwGender = User.objects.filter(gender=0).exclude(status='destroy').count()


    # 模板音頻
    aduioStoryCount = AudioStory.objects.filter(
      isDelete=False, audioStoryType=1, isUpload=1, createTime__range=(t1, t2)).count()

    # 自由錄制
    freedomStoryCount = AudioStory.objects.filter(
      isDelete=False, audioStoryType=0, isUpload=1, createTime__range=(t1, t2)).count()

    # 兒歌
    tags1 = Tag.objects.filter(code="RECORDTYPE", name='兒歌').first()
    tags1Count = tags1.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)).count()   # 兒歌作品數(shù)
    user1Count = tags1.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)).\
      values('userUuid_id').annotate(Count('userUuid_id')).count()                # 錄音類型人數(shù),去重

    # result = Tag.objects.filter(code="RECORDTYPE").annotate(Count('tagsAudioStory'))

    # 父母學(xué)堂
    tags2 = Tag.objects.filter(code="RECORDTYPE", name='父母學(xué)堂').first()
    tags2Count = tags2.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)).count()
    user2Count = tags2.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)).\
      values('userUuid_id').annotate(Count('userUuid_id')).count()

    # 國(guó)學(xué)
    tags3 = Tag.objects.filter(code="RECORDTYPE", name='國(guó)學(xué)').first()
    tags3Count = tags3.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)).count()
    user3Count = tags3.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)).\
      values('userUuid_id').annotate(Count('userUuid_id')).count()

    # 英文
    tags4 = Tag.objects.filter(code="RECORDTYPE", name='英文').first()
    tags4Count = tags4.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)).count()
    user4Count = tags4.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)). \
      values('userUuid_id').annotate(Count('userUuid_id')).count()

    # 其他
    tags5 = Tag.objects.filter(code="RECORDTYPE", name='其他').first()
    tags5Count = tags5.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)).count()
    user5Count = tags5.tagsAudioStory.filter(isDelete=False, createTime__range=(t1, t2)).\
      values('userUuid_id').annotate(Count('userUuid_id')).count()

    recordTypePercentage = [
      {'name': '兒歌', 'tagsNum': tags1Count, 'userNum': user1Count},
      {'name': '兒歌', 'tagsNum': tags2Count, 'userNum': user2Count},
      {'name': '國(guó)學(xué)', 'tagsNum': tags3Count, 'userNum': user3Count},
      {'name': '英文', 'tagsNum': tags4Count, 'userNum': user4Count},
      {'name': '其他', 'tagsNum': tags5Count, 'userNum': user5Count}
    ]

    # 活躍用戶排行
    data1_list = []
    # result = AudioStory.objects.filter(isDelete=False, createTime__range=(t1, t2)).values('userUuid_id').annotate(Count('userUuid_id'))[:1]
    res = User.objects.annotate(audioStory_count_by_user = Count("useAudioUuid")).order_by('-audioStory_count_by_user')[:5]
    for index,item in enumerate(res.values()):
      data = {
        'orderNum': index+1,
        'name': item['nickName'],
        'recordCount': item['audioStory_count_by_user']
      }
      data1_list.append(data)
    # 熱門錄制排行
    data2_list = []
    res = Story.objects.filter(status="normal", createTime__range=(t1, t2)).order_by('-recordNum')[:5]
    for index,item in enumerate(res.values()):
      data = {
        'orderNum': index + 1 or -1,
        'name': item['name'] or '',
        'recordNum': item['recordNum'] or 0
      }
      data2_list.append(data)

    # 熱門播放排行
    data3_list = []
    audioStory = AudioStory.objects.filter(isDelete=False, createTime__range=(t1, t2)).order_by('-playTimes')[:5]
    for index,item in enumerate(audioStory):
      data = {
        'orderNum': index + 1,
        'name': item.storyUuid.name if item.audioStoryType else item.name,
        'playTimes': item.playTimes
      }
      data3_list.append(data)

    # 圖表數(shù)據(jù)--新增用戶
    graph1 = User.objects.filter(createTime__range=(t1, t2)).\
      extra(select={"time": "DATE_FORMAT(createTime,'%%Y-%%m-%%e')"}).\
      order_by('time').values('time')\
      .annotate(userNum=Count('createTime')).values('time', 'userNum')
    if graph1:
      graph1 = list(graph1)
    else:
      graph1 = []

    # 活躍用戶
    graph2 = LoginLog.objects.filter(createTime__range=(t1, t2), isManager=False). \
      extra(select={"time": "DATE_FORMAT(createTime,'%%Y-%%m-%%e')"}). \
      values('time').annotate(userNum=Count('createTime', distinct=True)).values('time', 'userNum')
    if graph2:
      graph2 = list(graph2)
    else:
      graph2 = []

    return http_return(200, 'OK',
              {
                'totalUsers': totalUsers,      # 總用戶人數(shù)
                'totalAudioStory': totalAudioStory, # 音頻總數(shù)
                'totalAlbums': totalAlbums,     # 總的專輯數(shù)
                'newUsers': newUsers,        # 新增用戶人數(shù)
                'activityUsers': activityUsers,   # 活躍用戶人數(shù)
                'newAudioStory': newAudioStory,   # 新增音頻數(shù)
                'activityUsersRank': data1_list,   # 活躍用戶排行
                'male': male,             # 男性
                'female': female,           # 女性
                'unkonwGender': unkonwGender,    # 未知性別
                'aduioStoryCount': aduioStoryCount, # 模板音頻數(shù)量
                'freedomStoryCount': freedomStoryCount, # 自由錄制音頻數(shù)量
                'recordTypePercentage': recordTypePercentage,
                'hotRecordRank': data2_list,     # 熱門錄制排行
                'hotPlayAudioStoryRank': data3_list,   # 熱門播放排行
                'newUserGraph': graph1,       # 新增用戶折線圖
                'activityUserGraph': graph2,     # 活躍用戶折線圖
              })

補(bǔ)充知識(shí):Django 對(duì)符合條件的某個(gè)字段進(jìn)行求和,聚合函數(shù)annotate()

開(kāi)發(fā)環(huán)境:Ubuntu16.04+Django 1.11.9+Python2.7

對(duì)符合條件的某個(gè)字段求和 

之前在開(kāi)發(fā)的時(shí)候,有同事問(wèn)Django是否存在著這樣的方法,可以直接將符合條件的某個(gè)字段直接求和.

當(dāng)時(shí)不知道這樣的方法是否存在,但是想了想自己解決這類似問(wèn)題的方法,先用filter將符合條件的取出來(lái),然后進(jìn)行for循環(huán),取出需要的字段,進(jìn)行求和.感覺(jué)是挺low的,于是一起B(yǎng)aidu,寫代碼測(cè)試最后找到了可以求值的方法,聚合函數(shù)annotate().

from django.db.models import Sum
from models import Book
all_price = Book.objects.values('price').annotate(num_books=Sum('price')).filter(author='Yu')
print all_price[0]['num_books']

輸出結(jié)果:650

上面的參數(shù)換個(gè)順序,不會(huì)出錯(cuò)但不符合預(yù)期結(jié)果.

all_price = Book.objects.annotate(num_books=Sum('price')).filter(author='Yu').values('price')
print all_youxibi[0]['num_books']

輸出結(jié)果:'nums_book'

以上這篇Django ORM實(shí)現(xiàn)按天獲取數(shù)據(jù)去重求和例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 一款Python工具制作的動(dòng)態(tài)條形圖(強(qiáng)烈推薦!)

    一款Python工具制作的動(dòng)態(tài)條形圖(強(qiáng)烈推薦!)

    有時(shí)為了方便看數(shù)據(jù)的變化情況,需要畫(huà)一個(gè)動(dòng)態(tài)圖來(lái)看整體的變化情況,下面這篇文章主要給大家介紹了一款Python工具制作的動(dòng)態(tài)條形圖的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-02-02
  • GCN?圖神經(jīng)網(wǎng)絡(luò)使用詳解?可視化?Pytorch

    GCN?圖神經(jīng)網(wǎng)絡(luò)使用詳解?可視化?Pytorch

    這篇文章主要介紹了GCN?圖神經(jīng)網(wǎng)絡(luò)使用詳解?可視化?Pytorch,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • Python找出微信上刪除你好友的人腳本寫法

    Python找出微信上刪除你好友的人腳本寫法

    在本篇文章中我們給大家分享了Python找出微信上刪除你好友的人腳本寫法以及相關(guān)實(shí)例代碼,有需要的朋友們參考下。
    2018-11-11
  • 如何運(yùn)行.ipynb文件的圖文講解

    如何運(yùn)行.ipynb文件的圖文講解

    今天小編大家分享一篇如何運(yùn)行.ipynb文件的圖文講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-06-06
  • 使用Python進(jìn)行PDF文檔處理的常見(jiàn)操作

    使用Python進(jìn)行PDF文檔處理的常見(jiàn)操作

    使用 Python 進(jìn)行 PDF 文檔處理可以通過(guò)多種庫(kù)來(lái)實(shí)現(xiàn),包括 PyPDF2、pdfplumber、reportlab、pdfminer 等,這些庫(kù)可以處理不同的 PDF 任務(wù),以下是幾種常見(jiàn)操作及對(duì)應(yīng)的庫(kù)和代碼示例,感興趣的小伙伴跟著小編一起來(lái)看看吧
    2024-09-09
  • Pycharm無(wú)法正常安裝第三方庫(kù)的幾條應(yīng)對(duì)方法匯總

    Pycharm無(wú)法正常安裝第三方庫(kù)的幾條應(yīng)對(duì)方法匯總

    在使用pycharm學(xué)習(xí)python的時(shí)候,經(jīng)常需要第三方庫(kù),沒(méi)有第三方庫(kù)程序就會(huì)報(bào)錯(cuò),下面這篇文章主要給大家介紹了關(guān)于Pycharm無(wú)法正常安裝第三方庫(kù)的幾條應(yīng)對(duì)方法,需要的朋友可以參考下
    2023-04-04
  • Centos Python2 升級(jí)到Python3的簡(jiǎn)單實(shí)現(xiàn)

    Centos Python2 升級(jí)到Python3的簡(jiǎn)單實(shí)現(xiàn)

    下面小編就為大家?guī)?lái)一篇Centos Python2 升級(jí)到Python3的簡(jiǎn)單實(shí)現(xiàn)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-06-06
  • Python實(shí)現(xiàn)監(jiān)控一個(gè)程序的運(yùn)行情況

    Python實(shí)現(xiàn)監(jiān)控一個(gè)程序的運(yùn)行情況

    這篇文章主要為大家介紹了Python如何實(shí)現(xiàn)監(jiān)控一個(gè)程序的運(yùn)行情況,然后視情況將進(jìn)程殺死并重啟,文中的示例代碼簡(jiǎn)潔易懂,需要的可以參考一下
    2023-05-05
  • Python3進(jìn)制之間的轉(zhuǎn)換代碼實(shí)例

    Python3進(jìn)制之間的轉(zhuǎn)換代碼實(shí)例

    這篇文章主要介紹了Python3進(jìn)制之間的轉(zhuǎn)換代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • Python如何爬取51cto數(shù)據(jù)并存入MySQL

    Python如何爬取51cto數(shù)據(jù)并存入MySQL

    這篇文章主要介紹了Python如何爬取51cto數(shù)據(jù)并存入MySQL,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08

最新評(píng)論

桦甸市| 星子县| 锦屏县| 历史| 呼和浩特市| 五指山市| 佛教| 柯坪县| 丹东市| 涿州市| 大渡口区| 阳原县| 佛冈县| 博爱县| 茂名市| 苗栗县| 保靖县| 镇康县| 阜平县| 金山区| 沅陵县| 石景山区| 安陆市| 浪卡子县| 扶绥县| 灯塔市| 永嘉县| 灌云县| 开原市| 屏南县| 宁津县| 百色市| 青州市| 万宁市| 濮阳县| 伊春市| 永和县| 叙永县| 乐陵市| 吉林市| 沅江市|