Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I filter the imagefield by filename in django

I add a ImageField in my model like

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:

UserImage.objects.filter(photo.filename='a.jpg')
....
like image 459
LisztLi Avatar asked Dec 23 '11 05:12

LisztLi


People also ask

Can you filter by property Django?

Django-property-filter is an extension to django-filter and provides functionality to filter querysets by class properties. It does so by providing sub-classes for Filters and Filtersets to keep existing django-filter functionality. For more details and examples check the documentation.

What filter returns in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How can I get image name in Django?

You can obtain such name with os. path. splitext [Python-doc] to split a filename in the "root" and the "extension".


2 Answers

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. The query should then do something similar, for example:

UserImage.objects.filter(photo='images/users/photos/a.jpg')

like image 133
Abid A Avatar answered Oct 21 '22 01:10

Abid A


The above answer will correctly work moreover you can use icontains too as i am using

comment_qs = Upload.objects.filter(title__icontains=str(file_name)).filter(content_type__model='Task')

like image 24
Ankit Kumar Avatar answered Oct 21 '22 02:10

Ankit Kumar