简体   繁体   English

Django模型中的Override Field属性

[英]Override Field attribute in Django Model

I have a problem. 我有个问题。 I'm trying to change the directory on which a file gets uploaded, using the upload_to attribute of a FileField, without success. 我正在尝试使用FileField的upload_to属性更改文件上传到的目录,但没有成功。

The main issue is that I have defined a parent class, with a file attribute, and I want to change the directory on the child class. 主要问题是我已经定义了具有文件属性的父类,并且我想更改子类的目录。

My models are defined in this way : 我的模型是以这种方式定义的:

class DocumentBase(models.Model):
    file = models.FileField(upload_to=get_filename)


class Document(DocumentBase):
    file_type = models.CharField(max_size=150)

I tried to overwrite the FileField in the child class, without success (I'm aware now that this is not possible.) 我试图覆盖子类中的FileField,但没有成功(我现在知道这是不可能的。)

I also tried the answers on this other question (that is very similar to my problem), without success. 我还尝试了另一个问题 (与我的问题非常相似)的答案,但没有成功。

Could somebody help me with this? 有人可以帮我吗? Thanks! 谢谢!

As Willem said this can be solved monkey patching the upload_to attribute. 正如Willem所说,这可以解决猴子修补upload_to属性的问题。 But it didn't work for this case. 但这不适用于这种情况。

Digging into the FileField class definition , this class has another attribute: generate_filename . 深入研究FileField类定义 ,该类具有另一个属性: generate_filename This attribute is filled when upload_to is callable. 可调用upload_to时填充此属性。 This attribute is used to generate the file filename. 此属性用于生成文件名。

So, the solution that worked was : 因此,有效的解决方案是:

class DocumentBase(models.Model):
    file = models.FileField(upload_to=get_filename)


class Document(DocumentBase):
    file_type = models.CharField(max_size=150)

Document._meta.get_field('file').generate_filename = other_get_filename

This behavior changes on Django 1.10. 此行为在Django 1.10上发生了变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM