我试图基于同一模型中的另一个字段来保存我的模型字段。
例如:
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
def baby_boomer_status(self):
import datetime
if self.birth_date < datetime.date(1945, 8, 1):
return "Pre-boomer"
elif self.birth_date < datetime.date(1965, 1, 1):
return "Baby boomer"
else:
return "Post-boomer"
my_try = models.CharField(max_length=50, default=baby_boomer_status) #it does not work
当我在对象中更改birth_date时,我如何才能始终保存my_try。要在我的领域my_try
中获得“前婴儿潮”或“婴儿潮”的价值。
任何帮助将不胜感激。
答案 0 :(得分:1)
覆盖 save()
方法
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
my_try = models.CharField(max_length=50, null=True, blank=True)
def save(self, *args, **kwargs):
created = not self.pk
super().save(*args, **kwargs)
if created:
self.my_try = self.baby_boomer_status()
self.save()
def baby_boomer_status(self):
import datetime
if self.birth_date < datetime.date(1945, 8, 1):
return "Pre-boomer"
elif self.birth_date < datetime.date(1965, 1, 1):
return "Baby boomer"
else:
return "Post-boomer"
将保存方法更改为
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
Person.objects.filter(pk=self.pk).update(my_try=self.baby_boomer_status())