Django filter between two date - django

My django model datetime field is string. In this case, how to get data between two dates?
models.py
class asdf(models.Model):
recordDate = models.CharField(max_length=20,blank=True)

Change the 'recordDate' to DateField and use the following query:
asdf.objects.filter(recordDate__gte='2019-03-01', recordDate__lte='2019-03-09')

In order to get between range use filter this query:
models.asdf.objects.filter(recordDate__gte='start_date', recordDate__lt='end_date')
start_date and end_date may be string in date formats or datetime parsed object.

This is working for me
remember one thing what you are storing in you db means only date or datetime
when datetime
start = '2021-08-12 21:52:33.118649'
end = '2021-08-13 06:30:46.909572'
user = UserAccount.objects.filter(created_at__gte=start,
created_at__lte=end)
print user
when date
start = '2021-08-12'
end = '2021-08-13'
user = UserAccount.objects.filter(created_at__gte=start,
created_at__lte=end)
print user
or you can filter by using __range here also
start = '2021-08-12 21:52:33.118649'
end = '2021-08-13 06:30:46.909572'
user = UserAccount.objects.filter(created_at__range=(start, end))
print user
if you you are storing in db datatime and you want to retrieve only date from db
from datetime import datetime
datetime.strptime('2014-12-04', '%Y-%m-%d').date()

Related

Getting a query set between a range of dates Django

I'm trying to return a list of items in between 2 different dates, a date in the past and the current time using a queryset.
The error I'm getting is TypeError: an integer is required (got type str)
views.py
import datetime
import pytz
first_date = "2020-01-01 19:17:35.909424"
last_date = timezone.now()
I don't want anything returned that has a date in the future
Here is the filter in the query
.filter(hide_sentance_until=(date(first_date), date(last_date)))
This is the full queryset, but it's the above filter causing he issue
zip_flash_sentances = (
model.objects
.filter(show_sentance=True)
.filter(
hide_sentance_until=(date(first_date), date(last_date))
)
.order_by("?")
.filter(username_id = user_id_fk)
.values_list('sentance_eng', 'sentance_esp', 'id')
.first()
)
I thought it might be a comparison problem with dates but here is my model field
models.py
hide_sentance_until = models.DateTimeField(default=datetime.now(), blank=True)
Thanks
You can use gte and lte query attributes:
first_datetime = datetime.datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S.%f')
last_date = timezone.now()
.filter(hide_sentance_until__lte=last_date,hide_sentance_until__gte=first_time)
One thing is that you're specifying a specific value that's determined when your code is compiled to be your default value. To have the actual current date be the value you want:
hide_sentance_until = models.DateTimeField(default=datetime.now, blank=True)
Then you need to parse the datetime out of the string.
date_value = datetime.strptime(first_date, DATETIME_FORMAT_YOU_USE)
Where DATETIME_FORMAT_YOU_USE is the series of format codes from Python that you're using.
Finally you should use the __range queryset field lookup.
.filter(
hide_sentance_until__range=(date_value, timezone.now())
)

How to filter django queryset with date and time?

This is my model field
start = models.DateTimeField(null=True,blank=True)
end = models.DateTimeField(null=True,blank=True)
Let's say I have value,
cmp_date = '2019-09-05 20:09:00'
event_exists = Event.objects.filter(start__gte=cmp_date, end__lte=cmp_date).first()
And in my database I have start as "2019-09-05 18:09:00.000000" and end as "2019-09-06 19:09:00.000000"
But this returns none.. I guess the problem is with the time? May I know how to filter with date and time?
You have to transform cmp_date to a datetime object
import datetime
cmp_date = datetime.datetime.strptime(cmp_date, "%Y-%m-%d %H:%M:%S")
and run the following:
event_exists = Event.objects.filter(start__lte=cmp_date, end__gte=cmp_date).first()

Filtering DateTime field with Date Field using Filter Set

How do I go about filtering a date time field with just a Date field.
With the model and filter below
http://localhost:8020/applications/?created=19-07-2017 returns an empty queryset even with records which have date created=19-07-2017 (The created date of the record in datetime
IN MY MODELS.PY
Class Application(models.Model):
created = models.DateTimeField(auto_now=False, auto_now_add=True)
IN MY FILTERS.PY
import django_filters
class ApplicationFilter(django_filters.FilterSet)
created = django_filters.DateTimeFilter( label='Created')
class Meta:
model = Application
fields = ['created']
Using contains works.
Use DateFilter instead and specify the date format
created=django_filters.DateFilter(input_formats=['%Y-%m-%d','%d-%m-%Y'],lookup_expr='icontains'
use contains
created = django_filters.DateTimeFilter(name='created',lookup_expr='contains')
maybe also need to change the dateformat , yyyy-mm-dd
in your filters.py write this:
import django_filters
class ApplicationFilter(django_filters.FilterSet)
class Meta:
model = Application
fields = {'created': '__all__'}
in your url :
http://localhost:8020/applications/?created__date=19-07-2017
Some of the answers below mention the use of lookup_expr='icontains'. Whilst this does work, it will yield incorrect results when the apps timezone is not UTC. This is because the date field returns the datetime stamp in UTC.
The result is that if an object has a date in UTC+2, of 2022-07-31 00:30, this will be returned as 2022-07-30 22:30, yielding incorrect results. It will be included in a filtered queryset of date 2022-07-30 and not 2022-07-31 as we expect.
Instead, we can the field name to return the date, where Django already does the conversion of the date using the specified timezone in the settings.py file. This can be done by using field_name='created__date' rather than lookup_expr='icontains' so that it is timezone aware.
created=django_filters.DateFilter(field_name='created__date')

Django Queryset - extracting only date from datetime field in query (inside .value() )

I want to extract some particular columns from django query
models.py
class table
id = models.IntegerField(primaryKey= True)
date = models.DatetimeField()
address = models.CharField(max_length=50)
city = models.CharField(max_length=20)
cityid = models.IntegerField(20)
This is what I am currently using for my query
obj = table.objects.filter(date__range(start,end)).values('id','date','address','city','date').annotate(count= Count('cityid')).order_by('date','-count')
I am hoping to have a SQL query that is similar to this
select DATE(date), id,address,city, COUNT(cityid) as count from table where date between "start" and "end" group by DATE(date), address,id, city order by DATE(date) ASC,count DESC;
At least in Django 1.10.5, you can use something like this, without extra and RawSQL:
from django.db.models.functions import Cast
from django.db.models.fields import DateField
table.objects.annotate(date_only=Cast('date', DateField()))
And for filtering, you can use date lookup (https://docs.djangoproject.com/en/1.11/ref/models/querysets/#date):
table.objects.filter(date__date__range=(start, end))
For the below case.
select DATE(date), id,address,city, COUNT(cityid) as count from table where date between "start" and "end" group by DATE(date), address,id, city order by DATE(date) ASC,count DESC;
You can use extra where you can implement DB functions.
Table.objects.filter(date__range(start,end)).extra(select={'date':'DATE(date)','count':'COUNT(cityid)'}).values('date','id','address_city').order_by('date')
Hope it will help you.
Thanks.

Django Mongoengine EmbeddedDocument query issue

my model is about a list of top movies
class Movie(Document):
title = StringField()
...
ranks = ListField(EmbeddedDocumentField('Rank'))
class Rank(EmbeddedDocument):
rank = IntField()
imdb_rating = FloatField()
date = StringField(required=True)
How can I write a query to get only the movies have Rank record in today?
I'd advise using a datetime object for date rather than a string as it seems more explicit. Either way you can easily find all Movie documents with a rank that has a date matching today like so:
Movie.objects(ranks__date__gte=datetime.today().date()) # using DateTimeField
or
Movie.objects(ranks__date="16/04/2012") # using StringField