重命名 django FileField 文件

发布于 2025-01-02 05:58:04 字数 421 浏览 0 评论 0原文

django 应用程序中添加了一些附加功能,因此 upload_to 功能也得到了扩展。

由于 django 默认将文件名存储在数据库中,文件存储在磁盘上,因此不会造成任何损害 - 新文件使用新的 upload_to 函数命名,而旧文件继续工作。

然而,这很混乱 - 我们最终会遇到这样的情况:

/media/userID/oldfilename.pdf 

/media/app/userID/projectID/newfilename.pdf 

没有办法批量重命名这些文件?我想这可以通过遍历数据库来完成,检查 FileField 中的路径是否与当前 upload_to 的结果匹配,如果不匹配,则重命名..这似乎是一个常见问题,所以也许有更通用的方法?

Some additional features were added to a django application, and as a result the upload_to function also expanded.

Since django by default stores filenames in the database, and files on disk, no harm has been done - new files are named using a new upload_to function, while old files continue to work.

However, this is messy - we end up in a situation with files like

/media/userID/oldfilename.pdf 

and

/media/app/userID/projectID/newfilename.pdf 

Is there a way to bulk rename those files? I guess it could be done by iterating through the database, checking if the path in FileField matches the result of current upload_to, and if not, rename.. it seems like a common problem, so perhaps there is a more generic way out there?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆梦 2025-01-09 05:58:04

简单的解决方案是编写自定义 Django 管理命令。您可以使用 Django 的标准 manage.py 运行该命令。

像这样的东西:

from django.core.management.base import BaseCommand, CommandError
from example.models import YourModel

class Command(BaseCommand):
    args = ''
    help = ''

    def handle(self, *args, **options):

        # Get all objects
        objects = YourModel.objects.all()

        for object in objects: # For each object

            # If old file path:
            if not 'userID/projectID' in objects.filefield.name:
                # Move the file, eg usign shutil http://docs.python.org/library/shutil.html#shutil.move
                # Update filefield
                # save object

The simple solution is to write a custom Django management command. You can run the command using Django's standard manage.py.

Something like this:

from django.core.management.base import BaseCommand, CommandError
from example.models import YourModel

class Command(BaseCommand):
    args = ''
    help = ''

    def handle(self, *args, **options):

        # Get all objects
        objects = YourModel.objects.all()

        for object in objects: # For each object

            # If old file path:
            if not 'userID/projectID' in objects.filefield.name:
                # Move the file, eg usign shutil http://docs.python.org/library/shutil.html#shutil.move
                # Update filefield
                # save object
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文