Reputation: 4306
Date is in string format in database
class A(models.Model):
date = models.CharField(max_length=50, blank=True, null=True)
Yah i know it should be date type. but now we have many records and we will soon change it to date type. For current status i want get the objects greater than particular date. So how can i use date__gte
example
objs = A.objects.filter(date__gte=datetime.now())
Is there any way to achieve this without converting date to datetime field.
Upvotes: 1
Views: 1418
Reputation: 2106
I am not sure if that works. What you can try is a custom manager. So you can create a manager for your model, add something like date_gte
and then convert the string to a datetime. Then you can user those operators as usual. That's a quick fix for now, but the best solution is to use a DateTimeField, which you want to do as far as I understood.
Example Manager:
from django.db import models
class MyManager(models.Manager):
def date_gte(self, date=datetime.now()):
items = []
for obj in self.all():
if datetime(obj.date) < date:
items.append(obj)
return items
Then you could call it like MyModel.objects.date_gte(date=datetime.now())
.
Note: This is an expensive query and you may need to convert the simple list into QuerySet object. I haven't tested it, so this example should only help you get started.
Upvotes: 1
Reputation: 997
What kind of string? if it is formatted to %Y%m%d
, you can use .extra()
method to do the query.
A.objects.extra(where=['date >= date_of_today'])
Upvotes: 0
Reputation: 6304
There is no way to do this without a conversion (either in Django or the database during the query) to a proper DateTime
type. You're trying to compare a datetime.datetime
to a str
. That won't work in normal Python and it won't work here.
Upvotes: 1