3 回答

TA貢獻1847條經(jīng)驗 獲得超7個贊
我不知道你為什么認為它很笨拙。當(dāng) PyCharm 檢測到某個方法不訪問類成員并因此可以轉(zhuǎn)換為靜態(tài)方法或函數(shù)時,這種情況經(jīng)常發(fā)生,PyCharm 甚至使它變得很方便。
最重要的是,Python 導(dǎo)入非常方便。是的,您可以從模塊外部訪問模塊函數(shù),語法與訪問類相同:通過點引用訪問成員。
模塊:
# 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貢獻1805條經(jīng)驗 獲得超10個贊
您可以將函數(shù)calculate_age保存到另一個文件中,然后將其導(dǎo)入到models.py文件的頂部。這將允許訪問內(nèi)部的所有類/方法/函數(shù)。

TA貢獻1865條經(jīng)驗 獲得超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 ,您可以創(chuàng)建一個共享類,它們都可以繼承。
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
添加回答
舉報