Apostolos
Apostolos

Reputation: 8121

query lookups in django using a models attribute attributes

I have an Image model that has an ImageField

class Image(models.Model):
    image = models.ImageField(upload_to="pictures")
    #some other speicific to model fields

I want to be able to look for an Image when what I know is the name of it (which is unique). E.g if you have MEDIA_ROOT set to path_to_media and you upload image.jpg to pictures under MEDIA_ROOT then image.jpg is stored under path_to_media/pictrues/image.jpg and pictures/image.jpg becomes the name of the image like

image = Image.objects.get(pk=1) #if the image has id 1
print image.image.name #that prints pictures/image.jpg according to the example above

I want to be able to get the image when I have the name of it which is unique. So I have

name = "pictures/image.jpg"
image = Image.objects.get(image__name=name)

But this won't do it. What I get is the following error message:

FieldError: Join on field 'image' not permitted. Did you misspell 'name' for the lookup type?

How can I query to get a model based on a attribute of each own field?

Upvotes: 0

Views: 80

Answers (1)

Arun G
Arun G

Reputation: 1688

try this

name = "pictures/image.jpg"
image = Image.objects.get(image=name)

or

image = Image.objects.get(image="pictures/image.jpg")

Upvotes: 3

Related Questions