3 回答
TA贡献1847条经验 获得超7个赞
我不知道你为什么认为它很笨拙。当 PyCharm 检测到某个方法不访问类成员并因此可以转换为静态方法或函数时,这种情况经常发生,PyCharm 甚至使它变得很方便。
最重要的是,Python 导入非常方便。是的,您可以从模块外部访问模块函数,语法与访问类相同:通过点引用访问成员。
模块:
# myapp/utils.py
def calculate_age(born):
today = datetime.date.today()
return (today.year - born.year - ((today.month, today.day) < (born.month, born.day)))
#otherapp/models.py
from myapp import utils
class UserProfile(models.Model):
def clean(self):
if utils.calculate_age(self.birthday) < 13:
raise ValidationError("no minors below 13 allowed")
TA贡献1865条经验 获得超7个赞
可以尝试诸如多重继承之类的东西吗?不太确定这会比您所做的事情的全局功能更好
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 = self.calculate_age(self.person_dob) # <- Used here too
super(Profile, self).save(*args, **kwargs)
def calculate_age(born):
today = datetime.date.today()
return (today.year - born.year - ((today.month, today.day) < (born.month, born.day)))
class ProfileManager(models.Manager, Profile):
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 = self.calculate_age(years_ago100) # <- Used here
profile = self.create(user=user, person_dob=years_ago100, person_age=age)
return
如果您不喜欢从 Profile 类继承整个 models.Model ,您可以创建一个共享类,它们都可以继承。
class Profile(models.Model, helpers):
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 = self.calculate_age(self.person_dob) # <- Used here too
super(Profile, self).save(*args, **kwargs)
class ProfileManager(models.Manager, helpers):
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 = self.calculate_age(years_ago100) # <- Used here
profile = self.create(user=user, person_dob=years_ago100, person_age=age)
return
class helpers():
def calculate_age(self, born):
today = datetime.date.today()
return (today.year - born.year - ((today.month, today.day) < (born.month, born.day)))
def other_shared_method(self):
pass
添加回答
举报