开发者

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.DateFi开发者_Go百科eld()

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.


Did you have a look at django's Models' methods? You can find them here

class Event(models.Model):
    event_date = models.DateField()

    def get_season(self):
        import datetime
        """
        Returns the event's specific season
        """
        if 1 <= datetime.date.today().month < 4:
            return "Winter event"

Obviously the code above in incorrect, but you know what to do.


You can simply use filter on a date range, using __gt (greater than) and __lt (less than) operators:

Event.objects.filter(event_date__gt=datetime.date(2011, 1, 1), event_date__lt=(datetime.date(2011,6,1))

Or you can write the semester into the db, you can for instance override the default save() method so this is done automatically whenever you save a new or existing event. So the model would be:

class Event(models.Model):
    event_date = models.DateField()
    semester = models.CharField(max_length=10)

def save(self, *args, **kwargs):
    # determine if the even is in the spring or fall
    if self.event_date.month in [1,2,3,4,5]
        self.semester = 'spring'
    elif self.event_date.month in [8,9,10,11,12]
        self.semester = 'fall'
    super(Event, self).save(*args, **kwargs) # Call the "real" save() method.

Then you can simple query Event.objects.filter(semester = 'spring')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜