【问题标题】:In Django, how to create file field database variable in a query?在 Django 中,如何在查询中创建文件字段数据库变量?
【发布时间】:2021-08-21 14:17:45
【问题描述】:

我知道如何在views.py 中创建一个简单的查询变量,但我不知道它代表什么。例如,models.py 中有一个名为 age 的 CharFiled(模型名称为 Information)。要将单行数据存储在变量中,可以使用var1 = Information.objects.order_by('-id')[:1]var2 = Information.objects.order_by('-id')[:1].get()

据我了解,var1 存储查询集列表,var2 存储实际对象。如果我错了,请纠正我。这是否意味着 var2 具有数据库中年龄参数的实际值?如果不是,那么 var2 只是指向那个位置?

此外,假设models.py 中有一个名为userfile 的FileFiled 以及age,它接收用户想要存储在数据库中的任何文件。假设文件是​​通过表单上传的,并且整个上传功能工作正常。现在我想将 userfile 减半,因此我首先需要将文件的数据存储在一个变量中。我可以做file_data = var2.userfilefile_data = var1.userfile 吗?同样,file_data 中会包含什么? DB中文件的路径或实际文件或其他文件?如果没有,那么如何将文件的数据存储到变量中以便我可以使用它? (Django 3.2 版)

非常感谢!

【问题讨论】:

    标签: python django file django-views django-queryset


    【解决方案1】:

    你需要先了解 Django ORM:

    当您执行 Information.objects.earliest("id") 时: 您将在数据库中执行查询

    当您执行 var2 = Information.objects.earliest("id") 时: 数据库中什么都不做,调用var2时会在数据库中执行

    这叫懒惰:https://docs.djangoproject.com/fr/2.2/topics/db/optimization/#understand-queryset-evaluation

    当您将文件保存在FileField 中时,您只需保存访问该文档的路径:

    var2.userfile 会给你FileFieldhttps://docs.djangoproject.com/en/3.2/ref/models/fields/#filefield-and-fieldfile

    你可以访问这个:

    FieldFile.name
    The name of the file including the relative path from the root of the Storage of the associated FileField.
    
    FieldFile.path
    A read-only property to access the file’s local filesystem path by calling the path() method of the underlying Storage class.
    

    所以你需要像这样打开文件:

    with open(var2.userfile.path, "rb") as f:
        file_data = f.read()
    

    【讨论】:

    • 好吧,查询集评估非常有意义。另外,现在我了解了文件字段并且它有效!谢谢,伙计!
    猜你喜欢
    • 2021-09-02
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多