如何在两个 Django 类之间共享 Python 方法?

我的 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 时有标准方法可以做到这一点吗?


桃花长相依
浏览 100回答 3
3回答

aluckdog

我不知道你为什么认为它很笨拙。当 PyCharm 检测到某个方法不访问类成员并因此可以转换为静态方法或函数时,这种情况经常发生,PyCharm 甚至使它变得很方便。最重要的是,Python 导入非常方便。是的,您可以从模块外部访问模块函数,语法与访问类相同:通过点引用访问成员。模块:# myapp/utils.pydef calculate_age(born):&nbsp; &nbsp; today = datetime.date.today()&nbsp; &nbsp; return (today.year - born.year - ((today.month, today.day) < (born.month, born.day)))#otherapp/models.pyfrom myapp import utilsclass UserProfile(models.Model):&nbsp; &nbsp; def clean(self):&nbsp; &nbsp; &nbsp; &nbsp; if utils.calculate_age(self.birthday) < 13:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise ValidationError("no minors below 13 allowed")

holdtom

您可以将函数calculate_age保存到另一个文件中,然后将其导入到models.py文件的顶部。这将允许访问内部的所有类/方法/函数。

莫回无

可以尝试诸如多重继承之类的东西吗?不太确定这会比您所做的事情的全局功能更好class Profile(models.Model):&nbsp; &nbsp; person_dob = models.DateField()&nbsp; &nbsp; person_age = models.IntegerField()&nbsp; &nbsp; objects = ProfileManager()&nbsp; &nbsp; def save(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; # Update to real age when user edits profile for the first time.&nbsp; &nbsp; &nbsp; &nbsp; self.person_age = self.calculate_age(self.person_dob)&nbsp; &nbsp; # <- Used here too&nbsp; &nbsp; &nbsp; &nbsp; super(Profile, self).save(*args, **kwargs)&nbsp; &nbsp; def calculate_age(born):&nbsp; &nbsp; &nbsp; &nbsp; today = datetime.date.today()&nbsp; &nbsp; &nbsp; &nbsp; return (today.year - born.year - ((today.month, today.day) < (born.month, born.day)))class ProfileManager(models.Manager, Profile):&nbsp; &nbsp; def create_profile(self, user, member):&nbsp; &nbsp; &nbsp; &nbsp; # Set default age to 100 years old when profile is created.&nbsp; &nbsp; &nbsp; &nbsp; years_ago100 = datetime.datetime.now() - datetime.timedelta(days=101 * 365)&nbsp; &nbsp; &nbsp; &nbsp; age = self.calculate_age(years_ago100)&nbsp; &nbsp; &nbsp; &nbsp;# <- Used here&nbsp; &nbsp; &nbsp; &nbsp; profile = self.create(user=user, person_dob=years_ago100, person_age=age)&nbsp; &nbsp; &nbsp; &nbsp; return如果您不喜欢从 Profile 类继承整个 models.Model ,您可以创建一个共享类,它们都可以继承。class Profile(models.Model, helpers):&nbsp; &nbsp; person_dob = models.DateField()&nbsp; &nbsp; person_age = models.IntegerField()&nbsp; &nbsp; objects = ProfileManager()&nbsp; &nbsp; def save(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; # Update to real age when user edits profile for the first time.&nbsp; &nbsp; &nbsp; &nbsp; self.person_age = self.calculate_age(self.person_dob)&nbsp; &nbsp; # <- Used here too&nbsp; &nbsp; &nbsp; &nbsp; super(Profile, self).save(*args, **kwargs)class ProfileManager(models.Manager, helpers):&nbsp; &nbsp; def create_profile(self, user, member):&nbsp; &nbsp; &nbsp; &nbsp; # Set default age to 100 years old when profile is created.&nbsp; &nbsp; &nbsp; &nbsp; years_ago100 = datetime.datetime.now() - datetime.timedelta(days=101 * 365)&nbsp; &nbsp; &nbsp; &nbsp; age = self.calculate_age(years_ago100)&nbsp; &nbsp; &nbsp; &nbsp;# <- Used here&nbsp; &nbsp; &nbsp; &nbsp; profile = self.create(user=user, person_dob=years_ago100, person_age=age)&nbsp; &nbsp; &nbsp; &nbsp; returnclass helpers():&nbsp; &nbsp; def calculate_age(self, born):&nbsp; &nbsp; &nbsp; &nbsp; today = datetime.date.today()&nbsp; &nbsp; &nbsp; &nbsp; return (today.year - born.year - ((today.month, today.day) < (born.month, born.day)))&nbsp; &nbsp; def other_shared_method(self):&nbsp; &nbsp; &nbsp; &nbsp; pass
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python