2

Django (1.11) ORM using postgresql query is not able to compare date. I need data in between of leave_date_from and leave_date_to. I'm expecting one record.

My model is as follows:

class EmployeeLeaveApp(models.Model):
    user = models.ForeignKey(User, models.DO_NOTHING, on_delete=models.CASCADE)
    leave_date_from = models.DateField(blank=True, null=True)
    leave_date_to = models.DateField(blank=True, null=True)

My View query is :

inputdate = '2018-03-05'
duplicateleave = crm_models.EmployeeLeaveApp.objects.filter(
    leave_date_from__gte=inputdate,
    leave_date_to__lte=inputdate,
    user=user)

My table data is like below:

leave_date_from | leave_date_to | user
2018-03-01      | 2018-03-10    | 1
2018-03-07      | 2018-03-22    | 1

So far, I tried many solutions but no luck.

4
  • 1
    what are you getting now with this query? Commented Feb 12, 2018 at 12:09
  • No rows getting from this query. I should get one row Commented Feb 12, 2018 at 12:11
  • For this query you need two different dates to compare. Commented Feb 12, 2018 at 12:13
  • @sakthiselvam Why so? I need to check that input (date) is in between of particular record. Commented Feb 12, 2018 at 12:14

1 Answer 1

2
from datetime import datetime    
inputdate = datetime.strptime(inputdate, '%Y-%m-%d')    
duplicateleave = crm_models.EmployeeLeaveApp.objects.filter(
    leave_date_from__gte=inputdate,
    leave_date_to__lte=inputdate,
    user=user
)

==== OR ==== If error comes must be str, not datetime.date then use.

inputdate = datetime.strptime(str(inputdate), '%Y-%m-%d')
duplicateleave = crm_models.EmployeeLeaveApp.objects.filter(
    leave_date_from__gte=inputdate,
    leave_date_to__lte=inputdate,
    user=user
)

django expects a dateobject in the parameter, but you are passing string to it. so use this

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

5 Comments

Nope, not working. Though I tried this solution from SO.
how are you passing the user parameter? can you show that?
I'm using REST Framework, so I got error due to your solution, so I type casted that to date to str like inputdate = datetime.strptime(str(inputdate), '%Y-%m-%d')
so are you getting data now?? and if not can you show your user value and how you are querying it?
Your part of solution got worked, please accept the edit, I'll except answer. Thanks.

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.