Как получить месяц из даты в моделях django
Я хочу сделать запрос и вернуть только месяц года поля даты из моих моделей, затем сравнить результат возврата с текущим месяцем года.
current_date = datetime.date.today()
_history = PayrollModel.objects.filter(employee_id_id=employee_id)
if(_history == None or _history.count() == 0):
return True
if(_history != None and _history.count() != 0):
# entity = _history.get(month_year=current_date)
for history in _history:
print(history.employee_id_id)
if(history.month_year__month != current_date.month and history.month_year.year == current_date.year):
return True
else:
return False
Фильтрация по месяцу является встроенной функцией кверисета. Вы не показываете модель History, поэтому я пишу так, как будто соответствующее поле штампа даты называется xdate (дата может читаться путано)
Поэтому вам необходимо дополнительно отфильтровать:
today = datetime.date.today()
current_year = today.year
current_month = today.month
_history = _history.filter( xdate__year = current_year, xdate__month = current_month)
for history in _history:
...
Напишите запрос следующим образом-
month_wise_sales = Order.objects\
.annotate(month=Cast('created_at', DateField()))\
.values('month')\
.annotate(total_sales=Sum('total_price'))
Если необходимо использовать в шаблонах Django, то вы можете использовать его-
{{ monthly_sales.month | date:"M"}}