Django ImageField:如何使upload_to参数依赖于self.id? [英] Django ImageField: how to make upload_to parameter dependent on self.id?

查看:307
本文介绍了Django ImageField:如何使upload_to参数依赖于self.id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Sup ose Sup ose ose I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I I认为将所有图像存储在一个文件夹中不是很聪明(在速度方面,因为需要一些时间才能在该文件夹中找到一百万张图像和更多图像之间找到一个图像)需要更多的时间来找到任何东西。

因此,作为一种变体,我们可以将该图像存储在不同的文件夹中(即使是几个级别的嵌套文件夹)。



例如:ID为1-1000的用户将其图像存储在文件夹1中; ID为1001-2000的用户将他们的图像存储在文件夹2中等等...



为此,我们需要 upload_to 参数必须是动态的(取决于用户ID,换句话说, self.id )。



或者也许有更好的方法来实现这种情况?



提前感谢!!!

解决方案

您可以在一个例子中定义一个函数作为upload_to参数:

  def upload_to_by_id(instance,filename):
如果instance.id:
#你已经有一个id(更新一个新文件的模型)
folder = str(self.id / 1000 +1)
else:
#也许你还没有id!这可能会发生很多...:/
folder ='tmp'

返回'%s /%s'%(文件夹,文件名)

希望这有帮助!


Supose there is a site with 1 million users, and they all have at least one profile image (maybe more).

I'm not sure, but I think that storing all that images in one folder is not very smart (in terms of speed, because there need some time to find one image between a million and more images in that folder need more time to find anything there).

So, as a variant we can store that images in different folders (even if few levels of nested folders).

For example: users with id 1-1000 will store their images in folder 1; users with id 1001-2000 will store their images in folder 2 and so on...

To do this we need upload_to parameter of ImageField must be dynamic (dependent on user id or in other words self.id).

Are there any ways to make it dynamic? Or maybe there are some more proper ways of implementing this scenario?

Thanks in advance!!!

解决方案

You can define a function as the upload_to parameter... in your case:

def upload_to_by_id(instance, filename):
    if instance.id:
        # you already have an id (updating a model with a new file)
        folder = str(self.id/1000 +1)
    else:
        # maybe you still don't have an id!! this can happen a lot... :/
        folder = 'tmp'

    return '%s/%s' % (folder, filename)

Hope this helps!

这篇关于Django ImageField:如何使upload_to参数依赖于self.id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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