3

I have a Django class with a FileField. I know that you can get the FileField's url, or path, by calling filefield.path, or filefield.url . I tried to query for all of those objects by their FileField's url using

media = MediaLibraryFile.objects.filter(media_file__url='some_key')

but I get this error.

Unsupported lookup 'url' for FileField or join on the field not permitted.

I looked around the web, and found that you can only use lookup fields on foreignkey related objects, so my question is how can you query objects by file field url if thats the case ? It seems like this would be a very common query performed.

This is what I get when I do a simple query on media_file with icontains

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 []>
TJB
  • 3,706
  • 9
  • 51
  • 102

2 Answers2

3

If you know exactly what you want to match you could do;

MediaLibraryFile.objects.filter(media_file__exact='some_key')

Or alternatively you could do a query like;

MediaLibraryFile.objects.filter(media_file__contains='some')

Just beware, the above is case sensitive. If you don't know the case, you can do filter(media_file__icontains='something')

The docs for field lookups are here; https://docs.djangoproject.com/en/2.0/topics/db/queries/#field-lookups

markwalker_
  • 12,078
  • 7
  • 62
  • 99
  • Hey Markwalker, unfortunately this didn't work. I edited my question with the above query. – TJB Mar 27 '18 at 21:44
  • @JBT don't forget, the filter is a database operation so can only use what's in the db field. The field stores the path relative to the `MEDIA_ROOT` setting so your empty queryset is expected behaviour. You can check the docs here; https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.FileField.storage – markwalker_ Mar 27 '18 at 22:01
0

I solved it by annotating the query value and making sure that the annotated value ends with the name of the file

query_value = "fullUrl/filename.pdf"
# file name => filename.pdf

media = MediaLibraryFile.objects.annotate(query_value=Value(query_value)).filter(query_value__endswith=F("media_file"))
Reddy Tintaya
  • 141
  • 2
  • 8