Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define range of months for any year on Django model?

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?

like image 846
Patrick Beeson Avatar asked Oct 10 '22 19:10

Patrick Beeson


1 Answers

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.

like image 62
Brandon Avatar answered Oct 12 '22 09:10

Brandon