2

I have a model which contains created_at DateTimeField. I want to filter the model to get all object created on this day, month till now.

For Example : Date = 21/06/2016 Now I want to get all objects created on 21/06 till now irrespective of year.

Edit: To be precise, I have model which stores Date of Birth of Users. I want to get all the users who were born on this day.

I tried using the __range, __gte, __month & __day. This things did not work.

  • @ShangWang I tried using the range, gte, __month& __day. This things did not work – Sunil Tatipelly Jun 21 '16 at 13:49
  • 1
    Then why don't you specify them in your question? You should always tell people what you have tried and what's not working. If you just throw your question out there, it gives people the impression that you are trying to let people write code for you. Besides, the more specific your question is, the more likely that people will help you. http://stackoverflow.com/help/how-to-ask – Shang Wang Jun 21 '16 at 14:06
  • @Sunil, what do you mean by they don't work? Do they throw an error? Or return an empty list (in which case did you check if the objects have the created_at values that match the condition)? Or does it return a partial result? Can you post your code so we can see what's going on? – Sreyantha Chary Jun 22 '16 at 03:37

4 Answers4

1

Thanks for your comments and answers. I have used this answer to solve the problem. I have removed the timedelta(days) from the code.

Community
  • 1
  • 1
0

An example of filtering outside of the queryset. Get the date u want and remove unwanted results

from datetime import datetime, timedelta

twodaysago = str(datetime.strptime(str(datetime.now().date()-timedelta(days=2)), '%Y-%m-%d')).split()[0]

now do your query and filter it like this, you may also do it in the query filter, but if u need some extra manipulations do it in your code

date_filtered = [x for x in query\
                if datetime.strptime(
                    x.get('created_at ', ''),
                    '%Y-%m-%d') > twodaysago
                ]
Ohad the Lad
  • 1,889
  • 1
  • 15
  • 24
0

Not sure if I understand the problem correctly, but try this:

before = datetime.date(2016, 06, 21)
today = datetime.date.today()

MyModel.objects.filter(
    created_at__month__range=(before.month, today.month),
    created_at__day__range=(before.day, today.day)
)
Todor
  • 15,307
  • 5
  • 55
  • 62
-1

From what I can understand from your question, you want to get all objects with the same date as today, irrespective of the year.

I would use something like this. See if this helps.

from datetime import datetime
today = datetime.now()

OneModel.objects.filter(created_at__day = today.day.__str__(), 
    created_at__month =  today.month.__str__())

For more see this link: How can I filter a date of a DateTimeField in Django?

Community
  • 1
  • 1
Sreyantha Chary
  • 656
  • 4
  • 13