欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

django之如何按日期查詢數(shù)據(jù)

 更新時(shí)間:2023年08月12日 15:19:42   作者:zhen24  
這篇文章主要介紹了django之如何按日期查詢數(shù)據(jù)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

django按日期查詢數(shù)據(jù)

1、數(shù)據(jù)庫模型 。

from django.db import models
class Get_time(models.Model):
    '''測(cè)試'''
    name = models.CharField(max_length=12)
    time= models.DateTimeField(auto_now_add=True)

2、序列化和分頁。 

from rest_framework import serializers
from knife_manage import models
class Get_time_Serializer(serializers.ModelSerializer):
    '''序列化'''
    class Meta:
        model = models.Get_time
        fields = '__all__'
class PageNumber(PageNumberPagination):
    '''分頁'''
    page_size = 50
    page_size_query_param = 'size'
    max_page_size = 5
    page_query_param = 'page'

3、路由。

url(r'^/test/$', views.Timeview.as_view({'get':'filter','post':'post'})),

4、視圖。

 
class Timeview(ModelViewSet):
    authentication_classes = []   # 取消用戶認(rèn)證
    queryset = models.Get_time.objects.all()
    serializer_class = Get_time_Serializer  # 序列化數(shù)據(jù)
    pagination_class = PageNumber()  # 分
    def filter(self, request, *args, **kwargs):
        """多條件查詢匹配"""
        queryset = models.Get_time.objects.filter(time__year = 2020) # 按年查詢
        queryset = models.Get_time.objects.filter(time__month = 12)  # 按月查詢
        queryset = models.Get_time.objects.filter(time__day= 9)  # 按日查詢
        now = datetime.datetime.now()
        start = now-datetime.timedelta(hours=12, minutes=0, seconds=0)
        queryset = models.Get_time.objects.filter(time__gt= start) # 大于某個(gè)日期
        queryset = models.Get_time.objects.filter(time__lt= start) # 小于某個(gè)日期
        start_date = datetime.date(2009, 1, 1)
        end_date = datetime.date(2020, 3, 31)
        queryset = models.Get_time.objects.filter(time__range=(start_date, end_date)) # 按區(qū)間查詢
        queryset = models.Get_time.objects.filter(time__week_day=4) # 按星期幾查詢
        pager_size = self.pagination_class.paginate_queryset(queryset=queryset, request=request, view=self)
        ser = self.serializer_class(instance=pager_size, many=True)
        return self.pagination_class.get_paginated_response(ser.data)
    def post(self, request, *args, **kwargs):
         """新增"""
        try:
            import random
            name=random.randint(10000,99999)
            return Response({'info': '操作成功!', 'code': 200})
        except Exception:
            return Response({'info': '操作失敗!', 'code': 400})

5、結(jié)果:

6、extra。

1)、用戶選擇日歷查詢。

range=['2019-03-04', '2019-06-24']  # 前臺(tái)傳過來的數(shù)據(jù)
start=[int(x) for x in range[0].split('-')]
end=[int(x) for x in range[1].split('-')]
start_date = datetime.date(start[0], start[1],start[2])
end_date = datetime.date(end[0],end[1],end[2])

 2)、用戶選擇特定日期。

未設(shè)置時(shí)區(qū)時(shí)的操作

request_time='2012-09-09'
time_split=[int(x) for x in request_time.split('-')]
times='%s-%s-%s'%(time_split[0],time_split[1],time_split[2]+1)
cday = datetime.strptime(times, '%Y-%m-%d')
models.Get_time.objects.create(name=name,time=cday)?

設(shè)置時(shí)區(qū)時(shí)的操作

配置文件設(shè)置時(shí)區(qū):

TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = False?

視圖:

request_time='2012-09-09'
cday = datetime.strptime(request_time, '%Y-%m-%d')
models.Get_time.objects.create(name=name,time=cday)

django ORM查詢指定日期范圍內(nèi)的數(shù)據(jù)

 dt_s= datetime.now().date()  # 2018-7-15
 dt_e = (dt_s- timedelta(7))  # 2018-7-08
 objs = Record.objects.filter(end_time__range=[dt_s, dt_e])
 objs = Record.objects.filter(Q(end_time__=dt_s) & Q(end_time__lt=dt_e)) # 效果相同

end_time為datetime類型數(shù)據(jù)

idend_timevalue
12018-07-09 04:23:161
22018-07-015 04:23:163

使用上面的命令返回的結(jié)果為第一條,以下是ORM封裝的SQL語句,因?yàn)?018-07-15 04:23:16 比 2018-07-15大

select * from record where end_time between 2018-07-08 and 2018-07-15;

You can use range anywhere you can use BETWEEN in SQL — for dates, numbers and even characters.
Warning
Filtering a DateTimeField with dates won’t include items on the last day, because the bounds are interpreted as “0am on >the given date”. If pub_date was a DateTimeField, the above expression would be turned into this SQL:
SELECT … WHERE pub_date BETWEEN ‘2005-01-01 00:00:00’ and ‘2005-03-31 00:00:00’;
Generally speaking, you can’t mix dates and datetimes.

要將end_time轉(zhuǎn)換為日期,就能返回兩條數(shù)據(jù)了

select * from record where date(end_time) between 2018-07-08 and 2018-07-15;

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 淺談Python實(shí)現(xiàn)Apriori算法介紹

    淺談Python實(shí)現(xiàn)Apriori算法介紹

    這篇文章主要介紹了淺談Python實(shí)現(xiàn)Apriori算法介紹,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-12-12
  • Python中文豎排顯示的方法

    Python中文豎排顯示的方法

    這篇文章主要介紹了Python中文豎排顯示的方法,可實(shí)現(xiàn)Python將中文豎排輸出顯示的功能,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-07-07
  • Python中re正則匹配數(shù)據(jù)的實(shí)現(xiàn)

    Python中re正則匹配數(shù)據(jù)的實(shí)現(xiàn)

    在Python中,可以使用re模塊來使用正則表達(dá)式,本文主要介紹了Python中re正則匹配數(shù)據(jù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-04-04
  • Python tkinter界面實(shí)現(xiàn)歷史天氣查詢的示例代碼

    Python tkinter界面實(shí)現(xiàn)歷史天氣查詢的示例代碼

    這篇文章主要介紹了Python tkinter界面實(shí)現(xiàn)歷史天氣查詢的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Python實(shí)現(xiàn)抓取頁面上鏈接的簡(jiǎn)單爬蟲分享

    Python實(shí)現(xiàn)抓取頁面上鏈接的簡(jiǎn)單爬蟲分享

    這篇文章主要介紹了Python實(shí)現(xiàn)抓取頁面上鏈接的簡(jiǎn)單爬蟲分享,本文使用了一個(gè)開源模塊requests實(shí)現(xiàn)需求,需要的朋友可以參考下
    2015-01-01
  • python報(bào)錯(cuò)解決之python運(yùn)行bat文件的各種問題處理

    python報(bào)錯(cuò)解決之python運(yùn)行bat文件的各種問題處理

    這篇文章主要介紹了python報(bào)錯(cuò)解決之python運(yùn)行bat文件的各種問題處理,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • 關(guān)于Python中空格字符串處理的技巧總結(jié)

    關(guān)于Python中空格字符串處理的技巧總結(jié)

    在我們?nèi)粘9ぷ髦薪?jīng)常會(huì)遇到字符串處理,大家應(yīng)該都不陌生,但空格字符串呢?會(huì)不會(huì)就不太熟悉了呢?所以下面這篇文章就來給大家總結(jié)了關(guān)于Python中空格字符串處理的技巧,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-08-08
  • Flask-藍(lán)圖?blueprint詳情

    Flask-藍(lán)圖?blueprint詳情

    這篇文章主要介紹了?Flask-藍(lán)圖?blueprint的相關(guān)資料,Blueprint?是一個(gè)存儲(chǔ)視圖方法的容器,這些操作在這個(gè)Blueprint?被注冊(cè)到一個(gè)應(yīng)用之后就可以被調(diào)用,F(xiàn)lask?可以通過Blueprint來組織URL以及處理請(qǐng)求,更多相關(guān)資料需要的小伙伴可以參考下面文章
    2021-11-11
  • Pytest中conftest.py的用法

    Pytest中conftest.py的用法

    conftest.py文件到底該如何使用呢,下面我們就來詳細(xì)了解一下conftest.py文件的特點(diǎn)和使用方法吧,感興趣的小伙伴們可以參考一下
    2021-06-06
  • python中print輸出有空格如何解決

    python中print輸出有空格如何解決

    這篇文章主要介紹了python中print輸出有空格的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02

最新評(píng)論