I need to filter queryset based on today/tommorows date and the field available is a date field not datetime field
I am using custom manager for providing filtered result
class CallbackReqManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter()
def callbacktoday(self):
today=date.today
print(today)
return self.filter(prefereddate=today)
class CallbackReq(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
query = models.CharField(max_length=150)
preferedtime = models.TimeField(auto_now=False, auto_now_add=False)
prefereddate = models.DateField(auto_now=False, auto_now_add=False)
requestedon = models.DateTimeField(auto_now_add=True)
attended = models.BooleanField(default=False) # whether call back is met
objects = CallbackReqManager()
but I am getting
TypeError: match = date_re.match(value)
TypeError: expected string or bytes-like object
You may want to write like this
today = date.today()
Let me know if some error still occurs.
You can add to new managers to your models, one for filtring by today's date and the other is by tomorrow's data. Here is an example
from datetime import date, timedalte
from django import models
class FilterByToday(models.Manager):
def get_queryset(self):
"""Filtering by today's date"""
return super().get_queryset().filter(
prefereddate=date.today()
)
class FilterByTomorrow(models.Manager):
"""
filtering by tomorrow's date
where: date.today() + timedelta(days=1)
is: Today + 1 day
"""
def get_queryset(self):
return super().get_queryset().filter(
prefereddate=date.today() + timedalte(days=1)
)
class CallbackReq(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
query = models.CharField(max_length=150)
preferedtime = models.TimeField(auto_now=False, auto_now_add=False)
prefereddate = models.DateField(auto_now=False, auto_now_add=False)
requestedon = models.DateTimeField(auto_now_add=True)
attended = models.BooleanField(default=False) # whether call back is met
# You can keep your default objects manager
objects = models.Manager()
# Today's manager
objects_today = FilterByToday()
# Tomorrow's manager
objects_tomorrow = FilterByTomorrow()
So, in your next code you can use, for example:
# Return all the Model's records without using the custom managers
instance = CallbackReq.objects.all()
# Return all Model's records by filtering them by today's date
instance = CallbackReq.objects_today.all()
# Return all Model's records by filtering them by tomorrow's date
instance = CallbackReq.objects_tomorrow.all()
For more informations visit the official documentation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.