【问题标题】:ValueError The QuerySet value for an exact lookup must be limited to one result using slicing on django viewsValueError 精确查找的 QuerySet 值必须限制为在 django 视图上使用切片的一个结果
【发布时间】:2019-11-10 08:14:11
【问题描述】:

我遇到了这个错误,我想不出解决方法,这里是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 的包含部分更改为

{% 包括“sellers/transaction_list.html” transaction_list=交易 %}

错误消失但交易未显示。

【问题讨论】:

  • 你能发布完整的回溯吗?
  • 它的简单帐户是包含多个结果的查询集,您正在尝试使用它过滤产品,这不允许获得单个帐户或使用 IN

标签: python html django django-views


【解决方案1】:

accounts 是一个QuerySet,这意味着它是一个包含零个、一个或多个SellerAccounts 的集合,因此您应该使用:

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

__in lookup [Django-doc] 也是如此。

话虽如此,您可以将上面的查询写成:

    def get_queryset(self):
        return Transaction.objects.filter(product__seller__user=self.request.user)

因此,您将在此处返回具有productTransactions,具有selleruser self.request.user

【讨论】:

    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2021-04-23
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多