python 如何在django中过滤datetime字段中的日期

9gm1akwq  于 2022-11-28  发布在  Python
关注(0)|答案(1)|浏览(133)
views.py
import datetime

from django.shortcuts import render
import pymysql
from django.http import HttpResponseRedirect
from facligoapp.models import Scrapper
from django.utils import timezone
import pytz

roles = ""
get_records_by_date = ""
def index(request):
    if request.method == "POST":
        from_date = request.POST.get("from_date")
        f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d')
        print(f_date)
        to_date = request.POST.get("to_date")
        t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d')
        print(t_date)
        global get_records_by_date
        get_records_by_date = Scrapper.objects.all().filter(start_time=f_date,end_time=t_date)
        print(get_records_by_date)
    else:
        global roles
        roles =  Scrapper.objects.all()
        return render(request, "home.html",{"scrappers": roles})

    return render(request, "home.html", {"scrappers": get_records_by_date})

models.py
from django.db import models
from django.db import connections
# Create your models here.
from django.utils import timezone
class Scrapper(models.Model):
    scrapper_id = models.IntegerField(primary_key=True)
    scrapper_jobs_log_id = models.IntegerField()
    external_job_source_id = models.IntegerField()
    start_time = models.DateField(default=True)
    end_time = models.DateField(default=True)
    scrapper_status = models.IntegerField()
    processed_records = models.IntegerField()
    new_records = models.IntegerField()
    skipped_records = models.IntegerField()
    error_records = models.IntegerField()

    class Meta:
        db_table = "scrapper_job_logs"

Database structure
我发布了f_date = 2022-11-24 00:00:00,t_date = 2022-11-24 00:00:00。我需要获取日期为2022-11-24的行start_time和end_time。有没有解决方案如何从日期时间字段中过滤数据。如果我传递f_date和t_date,我的〈QuerySet []〉为空。

tct7dpnv

tct7dpnv1#

我需要获取日期为2022-11-24的行start_time和end_time。
它是DateTimeField,因此使用__date查找比较其date,因此使用此查询集:

Scrapper.objects.filter(start_time__date=f_date,end_time__date=t_date)

相关问题