We have a "Committee" class and I need to ensure that any new committee has start and end dates (don't know why they're CharFields instead of Dates or even Ints, but that's not my call) that are after any existing instances. This works, but I would appreciate any general review as well as specifically on my solution to my test problem: When no Committees exist, my tests broke as noted in the comment. My solution worked but feels hacky.
class Committee(models.Model): start_year = models.CharField(max_length=4) end_year = models.CharField(max_length=4) def save(self, *args, **kwargs): # new committees need to ensure start and end dates are in the future if not self.pk: committee_set = Committee.objects.all() latest_start_year = committee_set.aggregate(Max('start_year'))["start_year__max"] latest_end_year = committee_set.aggregate(Max('end_year'))["end_year__max"] # in the test database when there are no other committees yet, these evaluate to # None and break the tests. Doesn't really affect production code otherwise. try: latest_start_year = int(latest_start_year) except TypeError: latest_start_year = 0 try: latest_end_year = int(latest_end_year) except TypeError: latest_end_year = 1 if not (self.start_year > latest_start_year): raise ValidationError("Start year (%s) must be greater than most recent " "Committee start year (%s)" % ( self.start_year, latest_start_year)) if not (self.end_year > latest_end_year): raise ValidationError("End year (%s) must be greater than most recent " "Committee end year (%s)" % (self.end_year, latest_end_year)) super(Committee, self).save(*args, **kwargs)