djangourlfilefield

Is it possible to query Django objects by their FileField's url attribute


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 []>

Solution

  • 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