Reputation: 6294
I'm going to do this query:
today = datetime.date.today()
year=today.year
month=today.month
news=News.objects.filter(date__year__lt = year,date__month__lt=month)
Note:News object has a field named date
but I get this error:
Join on field 'date' not permitted. Did you misspell 'year' for the lookup type?
what's your idea?
thanks in advance
Upvotes: 4
Views: 6229
Reputation: 71
One of way to filter data based on Date and month only in Django is
Sales.objects.filter(Date__month=month,Date__year=year)
Sales Model:
class Sales(models.Model):
Amount = models.FloatField(blank=True, null=True)
Date = models.DateField()
updated_at = models.DateTimeField(auto_now=True)
VAT = models.BooleanField(default=True)
class Meta:
ordering = ['id']
def __str__(self):
return "{}-{}".format(self.Amount,self.Date)
def class_name(self):
return self.__class__.__name__
Upvotes: 0
Reputation: 239440
You can't append __lt
onto to __year
or __month
. Only the last double-underscored bit is consider the qualifier, everything before it is treated as a traversal, i.e. Django will try to look up a field named year
on join table named date
, which is obviously not correct.
For something like this you'll need to just compare the date directly:
date = datetime.date(year, month, 1)
news = News.objects.filter(date__lt=date)
Upvotes: 12
Reputation: 5955
Django has trouble with certain lookups when working through a relation (e.g. date__year__*
). I think this is something they are working on for future versions.
Does this produce an acceptable result?
news = News.objects.filter(date__lt = datetime.date(year, month, 1))
Upvotes: 2