python - Django model update on fetch -
my model has field should change if it's within date range.
it this:
class election(models.model) start_date = models.datetimefield(verbose_name = 'start date') end_date = models.datetimefield(verbose_name = 'end date') active = models.booleanfield(default=false) def updateactive(self): = timezone.now() if self.start_date < , self.end_date > now: self.active=true else: self.active=false self.save()
right now, every time query model, call updateactive()
views.py
.
so, question is: there way call updateactive()
every time fetch election
object? or keeping constant updated?
any idea welcome.
the best method not have active
field @ in model. main reason when value can generated simple calculation, should not stored in database. second reason booleanfield cannot indexed , queries involving field slow. therefore not lose doing calculation instead of doing field. best way add custom queryset this:
class electionqueryset(models.queryset): def is_active(self): return self.filter(start_date__lt=timezone.now()).filter(end_date__gt=timezone.now())
now model simple.
class election(models.model): start_date = models.datetimefield(verbose_name = 'start date') end_date = models.datetimefield(verbose_name = 'end date')
objects = electionqueryset.as_manager()
now model realy simple.
class election(models.model): start_date = models.datetimefield(verbose_name = 'start date') end_date = models.datetimefield(verbose_name = 'end date') objects = electionqueryset.as_manager()
yes that's all. there no need update database everytime fetch object! can use simple method find out what's active or not
election.objects.is_active()
the result is_active queryset, , can chain usual
election.objects.is_active().filter(...)
if want check if election active in template can :
class election(models.model): def is_active() if self.start_date < , self.end_date > now: return true
Comments
Post a Comment