I have a data model in Django where I save photos uploaded by users. There's an attribute called image_file
in the Photo
model (of the type ImageField
) where - among other things - the image's url is stored. I can successfully access this url with item.image_file.url
in the template (and view) for instance.
However, I can't seem to be able to do the following in the view:
Photo.objects.filter(owner=user).order_by('-id').values('id','image_file.url')[:10]
I.e. For a particular user, I'm trying to get the 10 latest photo objects' image urls along with object ids. This gives me FieldError: Cannot resolve keyword 'image_file.url' into field
. Shouldn't this have worked?
I understand I can retrieve the entire object and do the filtering in the template, but I felt it's more optimal to solely retrieve the fields I actually need instead of the full object.
p.s. it's a postgresql backend and the underlying Storage class has been over-ridden
The url
is a property
, not a value in the database (FileField code) which is why you can't get to it from values()
. As far as I can see, you'd have to get the url
value separately...
You might want to take a look at only()
though. If you go that route, you should probably watch the SQL queries with something like Django Debug Toolbar. If the url
property tries to retrieve a field that wasn't included in only()
, it will likely make a separate SQL call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With