1

I have search option which user input from front end.

search = {"Date":"2016-02-07","Status":"pass" }

Then I am mapping with those values with column names in DB.

query_to_field_mapping = {"Date": "date","Status": "result"}

query = {query_to_field_mapping[key]: value for key, value in search.items()}

Now I have DateTimeField in DB. When I am using filter I am trying with below one:

result = Customer.objects.filter(**query)

Here am trying to filter as per date field & want to get the filtered record as well. I tried the same with no success .How can I proceed?

Any help ll be awesome!!!

I tried the some other question from SO: How can I filter a date of a DateTimeField in Django?

I couldn't get a way to solve my problem as there we are passing a column name 1 by 1 .But right now I am passing as dictionary.

Community
  • 1
  • 1
danny
  • 983
  • 1
  • 7
  • 13
  • "I tried the same with no success" - what did you try? – solarissmoke May 07 '16 at 03:48
  • Tried the ORM **result = Customer.objects.filter(**query)** – danny May 07 '16 at 03:57
  • Please see [Parsing a Datetime String into a Django DateTimeField](http://stackoverflow.com/questions/8636760/parsing-a-datetime-string-into-a-django-datetimefield). You need to pass a `datetime` object to the query instead of a date string. – solarissmoke May 07 '16 at 04:04
  • try `query_to_field_mapping = {"Date": "date__contains","Status": "result"}`. Most probably it is because your datetimefield contains values including time, but when you search, you are providing only a date string (without time), therefore a `2016-02-07` (your query param) is not equal to `2016-02-07T12:32:22` (a possible value in the DB) – iulian May 07 '16 at 04:53
  • @iulian Thanks a lot. You saved my time. Please answer the question. I will mark as correct answer – danny May 07 '16 at 05:06

1 Answers1

1

Your approach is the correct one. The reason why it doesn't work is because you filter for equality of datetime field by providing a date string, therefore a 2016-02-07 date (your query param) does not equal 2016-02-07T12:32:22 (a possible value in the DB).

To overcome this situation, use one of the field lookups possibilities from the link of your own question. As a specific example, let's use a contains field lookup, like so:

query_to_field_mapping = {"Date": "date__contains","Status": "result"}

Thus, when passing the query_to_field_mapping to .filter(), it will look for the date within the datetime that you need.

iulian
  • 5,494
  • 3
  • 29
  • 39