Skip to main content
 首页 » 编程设计

python之ValueError 精确查找的 QuerySet 值必须限制为使用 django View 上的切片的一个结果

2024年08月13日44三少

我遇到了这个错误,我想不出解决它的方法,这里是 views.py

class SellerTransactionListView(ListView): 
    model = Transaction 
    template_name = "sellers/transaction_list_view.html" 
 
    def get_queryset(self): 
        account = SellerAccount.objects.filter(user=self.request.user) 
        if account.exists(): 
            products = Product.objects.filter(seller=account) 
            return Transaction.objects.filter(product__in=products) 
        return [] 

模板transaction_list_view.html

{% extends "base.html" %} 
 
{% block content %} 
<h1>Transactions</h1> 
<ul> 
 
    {% include "sellers/transaction_list.html" with transaction_list=object_list %} 
 
</ul> 
{% endblock %} 

和 transaction_list.html

<table> 
<thead> 
<th>Product</th> 
<th>User</th> 
<th>order_id</th> 
<th>Sale Total</th> 
    <th></th> 
</thead> 
<tbody> 
{% for trans in transaction_list %} 
<tr> 
    <td>{{ trans.product }}</td> 
    <td>{{ trans.profile }}</td> 
  <td>{{ trans.order_id }}</td> 
    <td>{{ trans.amount }}</td> 
    <td>{{ trans.timestamp|timesince }} ago</td> 
</tr> 
{% endfor %} 
</tbody> 
</table> 

如果我将 transaction_list_view.html 的包含部分更改为

{% include "sellers/transaction_list.html" with transaction_list=transactions %}

错误消失但交易没有显示。

请您参考如下方法:

account是一个QuerySet,这意味着它是一个包含零个、一个或多个SellerAccount的集合,所以你应该使用:

products = Product.objects.filter(seller<b>__in</b>=account)

因此 __in lookup [Django-doc] .

话虽如此,您可以将上面的查询写成这样来使它更有效:

    def get_queryset(self): 
        return Transaction.objects.filter(<b>product__seller__user=self.request.user</b>)

因此,您将在此处返回具有 product 的 Transactions,该 seller 具有 user > self.request.user。