生成属性参数值的模型方法 [英] Model method to generate the value for a parameter of an attribute

查看:39
本文介绍了生成属性参数值的模型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在模型内创建一个方法,该方法可以在属性的参数上调用以填充它.我想这样做,但它给我一个错误 NameError:未定义名称'self'.

I want to create a method inside a model which can be called on a parameter of an attribute to populate it. I thought of doing it this way but it gives me an error NameError: name 'self' is not defined.

class Host(User):
    class Meta:
        verbose_name = "Host"
        verbose_name_plural = "Hosts"
    def gen_path(self):
        path = 'static/{userdir}'.format(userdir=self.email)
        os.mkdir(path)
        return path
    hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to=self.gen_path(), null=True)

对此有什么解决方法?

推荐答案

您可以创建将实例文件名作为 upload_to 的参数的方法>属性;

You can create method that takes instance and filename as parameter for upload_to attribute;

def gen_path(instance, filename):
    extension = filename.split(".")[-1]
    filename = f"{instance.email}.{extension}"
    return f"static/{filename}"


class Host(User):
    hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to=gen_path, null=True)

    class Meta:
        verbose_name = "Host"
        verbose_name_plural = "Hosts"

更多信息,请参阅文档

这篇关于生成属性参数值的模型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆