渲染时捕获DatabaseError

时间:2011-08-10 23:15:21

标签: django templates

错误:

TemplateSyntaxError at /some/location
Caught DatabaseError while rendering: more than one row returned by a subquery used as an expression

模特:

class Price(models.Model):
    supermarket = models.ForeignKey(SuperMarket)
    product = models.ForeignKey(Product)
    price = models.DecimalField(max_digits=6, decimal_places=2)

查询:

def costs_of_product(product, supermarkets):
    filter1 = Price.objects.filter(product=product)
    return filter1.filter(supermarket__in=supermarkets)

虽然productList的结果是costs_of_product的调用结果。

模板:

<ul>   
{% for pr in productList %}
    <li>{{ pr.supermarket }}: {{ pr.price }} € </li>
{% empty %}    
    <li>No products are available.</li>
{% endfor %}
</ul> 

问题: 为什么上述错误显示在模板中for的第一行?

编辑:在amateur的评论之后,我在视图中添加了这一行(没有上述代码段)。

supermarkets = [supermarket.id for supermarket in supermarkets]

然后我打电话给costs_of_product()它就有效了!非常奇怪的是,当我在函数costs_of_product()的主体中移动这一行时,它不起作用!

1 个答案:

答案 0 :(得分:0)

尝试使用Q.像这样:

from django.db.models import Q

def costs_of_product(product, supermarkets):
    filter1 = Price.objects.filter(Q(product=product) & Q(supermarket__in=supermarkets))
    return filter1

您在列表中使用过滤器,因此可能会导致错误。

至于地方 - 这是因为Django尝试渲染你得到的对象(是的,Django从你的函数中得到了一些东西),但不能这样做。

相关问题