I have to deal with a model for time periods, and those periods are different per country and for which some periods are BC and some are AD. So I added a model Period with a name and a start and end as integer fields. As dates won't do for 14000BC, I figured I would define negative years as BC and the positive as AD. Fields' start and end can be empty as the first period (name='First period', start=null, end=-14000) would read something like: "First period (before 14000 BC)" and the last period (name="Last period", start=1989, end=null) would read: "Last period (1989 - present)"
With my limited knowledge, I tried modifying the __str__
method of my model, first attempting to convert negative years to positive years and add the BC in the name.
The second issue I have is that without the conditional trials, the None fields are shown as None even though I have this in admin.py. It works for the list_display
but not for the name returned by __str__
.
@admin.register(Period)
class PeriodAdmin(admin.ModelAdmin):
list_display = ('name', 'country', 'start', 'end')
empty_value_display = '' # seems not to work on def __str__(self):!
Here is my model in models.py and this throws an error in my console:
class Period(models.Model):
country = models.ForeignKey('Country', on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=100, blank=True, null=True)
## use negative values for before start and end dates prior to BC and positive for AD
start = models.IntegerField(blank=True, null=True)
end = models.IntegerField(blank=True, null=True)
def __str__(self):
if self.start < 0:
A = f'{abs(self.start)} BC'
elif self.start == None:
A = ''
else:
A = self.start
if self.end < 0:
B = f'{abs(self.end)} BC'
elif self.end == None:
B = ''
else:
B = self.end
return f'{self.name} ({A} - {B})'
So what I'm trying to achieve is:
name: Meiji
start: 1868
end: 1912
Becomes in the admin: Meiji (1868-1912)
I can get this result using:
def __str__(self):
"""String for representing the Model object."""
return f'{self.name} ({self.start} - {self.end})'
However, consider this period with no end date:
name: Heisei
start: 1989
end: null
That would become: Heisei (1989-None)
despite the empty_value_display = ''
, it seems not to work in __str__
!
I want here: Heisei (1989 - present)
Even worse, periods with no start date:
name: Paleolithic
start: null
end: -14000
will become Paleolithic (None--14000)
, but I want: Paleolithic (before 14000 BC)
I tried to use some logic to achieve this:
def __str__(self):
if self.start < 0:
A = f'{abs(self.start)} BC'
elif self.start == None:
A = ''
else:
A = self.start
if self.end < 0:
B = f'{abs(self.end)} BC'
elif self.end == None:
B = ''
else:
B = self.end
return f'{self.name} ({A} - {B})'
But that seems not to work and gives an error in the runserver console: