我有一个带有 FileField 的 Django 类。我知道您可以通过调用 filefield.path 或 filefield.url 获取 FileField 的 url 或路径。我尝试使用
通过 FileField 的 url 查询所有这些对象media = MediaLibraryFile.objects.filter(media_file__url='some_key')
但是我得到了这个错误。
Unsupported lookup 'url' for FileField or join on the field not permitted.
我环顾了网络,发现您只能在外键相关对象上使用查找字段,所以我的问题是,如果是这样的话,您如何通过文件字段 url 查询对象?这似乎是一个非常常见的查询。
这是我使用 icontains 对 media_file 进行简单查询时得到的结果
In[27]: MediaLibraryFile.objects.all()[0].media_file.url
Out[27]: '/media/2017/6/13/444e35c2-0432-479a-805d-c46638ee3600.jpg'
In [28]: MediaLibraryFile.objects.filter(media_file__contains='/media/2017/6/13/444e35c2-0432-479a-805d-c46638ee3600.jpg')
Out[28]: <QuerySet []>
最佳答案
如果你确切地知道你想要匹配什么,你可以做;
MediaLibraryFile.objects.filter(media_file__exact='some_key')
或者您也可以执行如下查询;
MediaLibraryFile.objects.filter(media_file__contains='some')
请注意,以上是区分大小写的。如果你不知道大小写,你可以做 filter(media_file__icontains='something')
字段查找的文档在这里; https://docs.djangoproject.com/en/2.0/topics/db/queries/#field-lookups
关于django - 是否可以通过 FileField 的 url 属性查询 Django 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49522023/