使用模型属性属性在django中查询查找

时间:2014-07-09 09:18:42

标签: django django-queryset

我的Image模型有ImageField

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

我希望能够在我所知道的是它的名称(这是唯一的)时查找图像。例如,如果您将MEDIA_ROOT设置为path_to_media并将image.jpg上传到MEDIA_ROOT下的图片,则image.jpg会存储在path_to_media/pictrues/image.jpg下,而pictures/image.jpg会成为图片的名称像

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

我希望能够在我拥有唯一的名称时获取图像。所以我有

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

但这不会这样做。我得到的是以下错误消息:

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

如何根据每个字段的属性查询获取模型?

1 个答案:

答案 0 :(得分:3)

试试这个

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

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