“ QuerySet”对象没有属性“ images”

时间:2019-12-03 07:32:47

标签: django django-models django-views

我想检索属于数据库中某个字段的信息列表。但是,我收到的“ QuerySet”对象没有属性“ images”错误。

models.py

class Business(models.Model):
    business_name = models.CharField(max_length=50)
    business_location = models.CharField(max_length=200)
    business_description = models.TextField()

    def __str__(self):
        return self.business_name

 class BusinessImage(models.Model):
    business = models.ForeignKey(Business, related_name='images', on_delete =models.CASCADE)
    image = models.ImageField()

views.py

def get_data1(request, *args, **kwargs):
    b= Business.objects.filter(business_name="some-name")
    image_list = b.images.all()
    c = {'image_list': image_list}
    return render(request, "index.html", c)

使用此代码已解决此错误,但在模板中未看到任何内容: views.py

def get_data1(request, *args, **kwargs):
b= BusinessImage.objects.filter(business__business_name="some-name")
image_list = b.values_list('image',flat = True)
c = {'image_list': image_list}
return render(request, "index.html", c)

index.html

{% for i in image_list %}
  <img src ="{{ i.image.url}}">
{% endfor %}

2 个答案:

答案 0 :(得分:0)

对于您的情况,您需要使用values_list

b= Business.objects.filter(business_name="some-name")
image_list = b.values_list(
    'images',
     flat=True
).distinct(
    'images',
)

在模板中

{% for i in image_list %}
    <img src ="{{ i.images.url }}">
{% endfor %}

或者您可以直接获取图像:

b= Business.objects.filter(business_name="some-name")
image_list = b.values_list(
    'images__image',
     flat=True
).distinct(
    'images__image',
)

在模板中

{% for i in image_list %}
    <img src ="{{ i.url }}"> 
{% endfor %}

答案 1 :(得分:0)

过滤器将返回您必须为此使用for循环的查询集。而且它是图像而不是图像,请像这样修复。

def get_data1(request, *args, **kwargs):
b= BusinessImage.objects.filter(business__business_name="some-name")
image_list = b.values_list('image',flat = True)
c = {'image_list': image_list}
return render(request, "index.html", c)

更新问题后

b= BusinessImage.objects.filter(business__business_name="some-name")
return render(request, "index.html", b)

在index.html

{% for bb in b %}
        <img src="{{ bb.image.url }}">
{% endfor %}