Home > OS >  wanted to filter all the records created in last 24 hours with Django filter but timestamp stored ep
wanted to filter all the records created in last 24 hours with Django filter but timestamp stored ep

Time:10-17

problem context - I've a django model like this.

class UpdateRequests(models.Model):
    field_name = models.CharField(max_length=20)
    field_new_value = models.CharField(max_length=20)
    created_at = models.CharField(max_length=10)
    customer_id = models.CharField(max_length=50)
    request_status = models.CharField(max_length=20, choices=JOS_STATUS)
    request_close_date = models.CharField(max_length=20)

problem statement - I want to fetch all records created with in last 24 hours.

how I was trying - I was trying like this in my view function

time_threshold = datetime.now() - timedelta(days=1)

results = UpdateRequests.objects.filter(created_at__lte=time_threshold,
                                            request_status="Pending").values()

but it is not working and I guess because django __lte , __gte works on DateTimeField() only. reference - https://docs.djangoproject.com/en/4.1/ref/models/querysets/

Please help me with this, I don't want to change the schema since it's already in the production.

CodePudding user response:

Bruh you stored datetime in charfield created_at = models.CharField(max_length=10) How can db serve you Datetime Object? you have to make changes in Models and create objects again with this

created_at = models.DateTimeField(null=True,blank=True,auto_now_add=True)

auto_now_add=True Will fetch current datetime when you will Create Model object.

  • Related