I have a Django model called Event that has a date field for the date of the event:
class Event(models.Model):
event_date = models.DateField()
I'd like to be able to set a method on the model to tell whether the event is a "spring semester" event or a "fall semester" event.
The spring semester would be defined as January to May. Fall is August to December.
My goal is to be able to filter by either semester in a generic list of events for a year.
How would I go about writing the method defining each semester?
One approach is:
class SpringSemesterEventManager(models.Manager):
def get_query_set(self):
return super(SpringSemesterEventManager, self).get_query_set() \
.filter(is_spring_semester=True)
class FallSemesterEventManager(models.Manager):
def get_query_set(self):
return super(FallSemesterEventManager, self).get_query_set() \
.filter(is_fall_semester=True)
class Event(models.Model):
event_date = models.DateField()
@property
def is_spring_semester(self):
month = self.event_date.month
return True if month >= 1 and month <= 5 else False
@property
def is_fall_semester(self):
month = self.event_date.month
return True if month >= 8 and month <= 12 else False
objects = models.Manager()
spring_semester = SpringSemesterEventManager()
fall_semester = FallSemesterEventManager()
Then in a view you can do:
fall_events = Event.fall_semester.all()
Hope that helps you out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With