Reputation:
I'm attempting to channel a datetime field by month and year. Though no one can really say why while entering both month and year I get back a vacant set returned.
Model
class SpareParts(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
amount = models.IntegerField(blank=False, null=False)
date = models.DateField(blank=False, null=False)
And i want to filter on the basis of vehicle and month vise and here is mine view VIEWS.py
def view_spare(request):
sparepart = SpareParts.objects.all()
vehicle_filter = request.POST.get('vehicle') # get the value of the date field
month_filter = request.POST.get('month') # get the value of the date field
if vehicle_filter:
if month_filter:
sparepart = sparepart.filter(vehicle=vehicle_filter,date__month=month_filter).aggregate(Sum('amount'))
return render(request,'invoice/spare_parts_list.html',{'sparepart':sparepart})
and i want render the whole month sum of amount in template
Upvotes: 0
Views: 327
Reputation: 1094
date__month is an integer and according to your explanation “month” is a date field. So, you cannot compare them. You have to calculate the month and the year of your date input:
Do this:
import datetime
month_filter = datetime.datetime.strptime(self.request.POST.get('month'),"%d/%m/%Y").date() #Change with the formar that you are using.
And:
sparepart = sparepart.filter(vehicle=vehicle_filter,date__month=month_filter.month, date__year=month_filter.year).aggregate(Sum('amount'))
Upvotes: 1