models.py 中的函数是否应该驻留在类之外?

Cas*_*per 2 python django class django-models

在我的 models.py 中,我有几个类和几个管理器类。
我有一些方法是模型使用的通用方法,但不一定是模型的一部分。

例如:

def profile_photo_upload_loc(instance, filename):
        return "profile_photo/%s/%s" % (instance.user, filename)

class Profile(models.Model):
    profile_photo = models.ImageField(
        upload_to=profile_photo_upload_loc,
        null=True,
        blank=True,
        width_field='width_field',
        height_field='height_field',
        verbose_name='Profile Image',
    )  
Run Code Online (Sandbox Code Playgroud)

模型文件中的类之外可以有独立的函数吗?什么时候合适以及什么时候函数应该位于类内部?

Exp*_*tor 5

独立函数是那些可以在多个模型中使用的函数,例如您编写的函数可以在其他模型图像上传中使用,

那些写在模型类中的函数只能与该模型实例一起使用,而不能与其他模型一起使用,

如果您尝试将函数与其他模型实例一起使用,则会出现错误