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.

5
  • "I tried the same with no success" - what did you try? Commented May 7, 2016 at 3:48
  • Tried the ORM result = Customer.objects.filter(**query) Commented May 7, 2016 at 3:57
  • Please see Parsing a Datetime String into a Django DateTimeField. You need to pass a datetime object to the query instead of a date string. Commented May 7, 2016 at 4: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) Commented May 7, 2016 at 4:53
  • @iulian Thanks a lot. You saved my time. Please answer the question. I will mark as correct answer Commented May 7, 2016 at 5:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.