[英]How can I filter the imagefield by filename in django
I add a ImageField in my model like我在我的 model 中添加了一个 ImageField
class UserImage(models.Model):
photo = models.ImageField(upload_to='target_path')
....
after I save an image, let's say 'a.jpg', then I want user the filename 'a.jpg' to filter the model, what should I write like:保存图像后,假设为“a.jpg”,然后我希望用户使用文件名“a.jpg”来过滤 model,我应该这样写:
UserImage.objects.filter(photo.filename='a.jpg')
....
Your suggestion would give you an error.你的建议会给你一个错误。 Try this instead:
试试这个:
UserImage.objects.filter(photo='a.jpg')
Edit: Django prepends the upload_path to the file name.编辑:Django 在文件名前面加上了 upload_path。 The query should then do something similar, for example:
然后查询应该做类似的事情,例如:
UserImage.objects.filter(photo='images/users/photos/a.jpg')
The above answer will correctly work moreover you can use icontains too as i am using上面的答案将正确工作而且您也可以像我使用的那样使用 icontains
comment_qs = Upload.objects.filter(title__icontains=str(file_name)).filter(content_type__model='Task')
comment_qs = Upload.objects.filter(title__icontains=str(file_name)).filter(content_type__model='Task')
You need to query with the name of the photo
in the UserImage model.您需要使用UserImage model中的
photo
名称进行查询。
name = UserImage.objects.all()[0].photo.name
print(name)
media/a.jpg
UserImage.objects.filter(photo=name).all()
OR或者
UserImage.objects.filter(photo="media/a.jpg").all()
<QuerySet [<UserImage: UserImage object (1)>]>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.