开发者

Caught DatabaseError while rendering

开发者 https://www.devze.com 2023-03-26 23:03 出处:网络
The error: TemplateSyntaxError at /some/location Caught DatabaseError while rendering: more than one row returned by a subquery used as an expression

The error:

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

The mode开发者_运维百科l:

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

The query:

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

while the result of productList is the result of a call of costs_of_product.

The template:

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

The question: Why the aforementioned error is displayed at the first line of for in the template?

EDIT: Following the comment of amateur, I added this line in the view (none of the above snippets).

supermarkets = [supermarket.id for supermarket in supermarkets]

and then I called costs_of_product() and it worked! What is very curious is that when I move this line in the body of the function costs_of_product(), it does not work!


Try to use Q. Something like this:

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

You use filter on list, so this can possiibly cause an error.

As for place - it's because Django try to render objects you got (and yes, Django got something from your function), but can't do it.

0

精彩评论

暂无评论...
验证码 换一张
取 消