我的 Django models.py 文件中有两个类:
class ProfileManager(models.Manager):
def create_profile(self, user, member):
# Set default age to 100 years old when profile is created.
years_ago100 = datetime.datetime.now() - datetime.timedelta(days=101 * 365)
age = calculate_age(years_ago100) # <- Used here
profile = self.create(user=user, person_dob=years_ago100, person_age=age)
return
class Profile(models.Model):
person_dob = models.DateField()
person_age = models.IntegerField()
objects = ProfileManager()
def save(self, *args, **kwargs):
# Update to real age when user edits profile for the first time.
self.person_age = calculate_age(self.person_dob) # <- Used here too
super(Profile, self).save(*args, **kwargs)
每个类都使用这个calculate_age方法:
def calculate_age(born):
today = datetime.date.today()
return (today.year - born.year - ((today.month, today.day) < (born.month, born.day)))
如何使两个类都可以访问此方法?一种简单的方法是像这样使方法全局化,但这似乎是一种笨拙的方法:
def calculate_age(born):
...
class ProfileManager(models.Manager):
...
class Profile(models.Model):
...
另外,如果我想在这个特定模型模块之外访问该方法,这将不起作用。使用 Django 时有标准方法可以做到这一点吗?
aluckdog
holdtom
莫回无
相关分类