lostAtom
lostAtom

Reputation: 58

How to apply filter based on dates of an already existing database with Django Queryset

So i have the below's QuerySet output :

<QuerySet [{'price': 12.515, 'price_date': datetime.datetime(2017, 3, 13, 0, 0, tzinfo=)}, {'price': 12.335, 'price_date': datetime.datetime(2017, 3, 14, 0, 0, tzinfo=)}, {'price': 12.37, 'price_date': datetime.datetime(2017, 3, 15, 0, 0, tzinfo=)}, {'price': 12.35, 'price_date': datetime.datetime(2017, 3, 16, 0, 0, tzinfo=)}, {'price': 12.305, 'price_date': datetime.datetime(2017, 3, 17, 0, 0, tzinfo=)}...

How can i get say the price with price_date = 11-26-21 (November 26th 2021) ? Or if i want to filter by latest 30 prices?

Thanks

UPDATE 1:

When doing Product.objects.filter(price_date="2021-11-27")

I get the following runtime warning:

RuntimeWarning: DateTimeField product.price_date received a naive datetime (2021-11-26 00:00:00) while time zone support is active.
warnings.warn("DateTimeField %s received a naive datetime (%s)" <QuerySet []>

UPDATE 2:

When inputting '2021-09-28 08:38:13 CEST'. I get the below:

raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['�2021-09-28 08:38:13 CEST� value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']

Upvotes: 0

Views: 101

Answers (2)

Corralien
Corralien

Reputation: 120509

If you already have an initial QuerySet, you can still filter your results.

To extract the price, use values_list

prices = qs.filter(price_date='2021-11-26').values_list('price', flat=True)

Update

RuntimeWarning: DateTimeField product.price_date received a naive datetime (2021-11-26 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" <QuerySet []>

Use make_aware:

from datetime import datetime
from django.utils.timezone import make_aware

Product.objects.filter(price_date=make_aware(datetime(2021, 11, 26)))

Upvotes: 1

Nechoj
Nechoj

Reputation: 1582

You can use either datetime objects or strings inside the filter expression:

filter_date = datetime.now()
Product.objects.filter(price_date=filter_date)
Product.objects.filter(price_date__lte=filter_date)

# or
Product.objects.filter(price_date__lte="2021-11-27 20:00:00")
Product.objects.filter(price_date="2021-11-27")

For the last 30 items, you would order the query set according to the price_date reversed and then take the first 30 items.

Upvotes: 0

Related Questions