mercredi 4 juin 2014

Django - Filter based on model method


Vote count:

0




I have a model, defined like this :



class Item(models.Model):
name = models.CharField(max_length=200, null=True, default='', blank=True)
creation_date = models.DateTimeField('date created', default=timezone.now())

def was_published_today(self):
today = timezone.now() - datetime.timedelta(days=1)
return self.creation_date >= today


I would like to filter a set of Item like this :



items = Item.objects.filter(was_published_today=True)


But I run into a FieldError which makes sense as it seems that filter is not made to filter a set of objects based on a method. Detailed error :



Cannot resolve keyword 'was_published_today' into field. Choices are : creation_date, name


What is the correct way to do this ? I know I can compare creation_date with today's date but that's what was_published_today does and I would like to keep it DRY.



asked 35 secs ago

Simon

386





Aucun commentaire:

Enregistrer un commentaire