Home > OS >  How to filter the dates from datetime field in django
How to filter the dates from datetime field in django

Time:11-28

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

I post f_date = 2022-11-24 00:00:00 , t_date = 2022-11-24 00:00:00 . I need to get the row start_time and end_time which has dates 2022-11-24. Is there any solution how to filter datas from datetime field. If I pass f_date and t_date my <QuerySet []> is empty.

CodePudding user response:

I need to get the row start_time and end_time which has dates 2022-11-24.

It is a DateTimeField so compare its date using __date lookup so use this Queryset:

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