【问题标题】:Value Error saying The QuerySet value for an exact lookup must be limited to one result using slicing值错误说精确查找的 QuerySet 值必须使用切片限制为一个结果
【发布时间】:2021-08-05 16:55:57
【问题描述】:

我正在做一个项目,我正在尝试在购物车中添加产品,但我遇到了一个问题:ValueError at /onlineshopping/add-to-cart/p1/,这是位置。该逻辑还检查该项目是否当前存在于订单中以不创建重复项目。 我不明白我错在哪里。请帮帮我。

这里是 urls.py:

path('cart/', views.cart, name='cart'),
path('add-to-cart/<str:slug>/', add_to_cart, name='add-to-cart'),

这里是models.py:

class OrderItem(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(AffProduct, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

class Order(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    items = models.ManyToManyField(OrderItem)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField()
    ordered = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username

这里是views.py:

@login_required
def add_to_cart(request, slug):
    item = AffProduct.objects.filter(slug=slug)
    order_item = OrderItem.objects.get(
        item=item,
        user=request.user,
        ordered=False
    )
    order_qs = Order.objects.filter(user=request.user, ordered=False)
    if order_qs.exists():
        order = order_qs[0]
        # check if the order item is in the order
        if order.items.filter(item__slug=item.slug).exists():
            order_item.quantity += 1
            order_item.save()
            messages.info(request, "This item quantity was updated.")
            return redirect("cart")
        else:
            order.items.add(order_item)
            messages.info(request, "This item was added to your cart.")
            return redirect("cart")
    else:
        ordered_date = timezone.now()
        order = Order.objects.create(
            user=request.user, ordered_date=ordered_date)
        order.items.add(order_item)
        messages.info(request, "This item was added to your cart.")
        return redirect("cart")

这是我的购物车.html:

{% block content %}
  <main>
    <div class="container">

    <div class="table-responsive text-nowrap">
    <h2>Order Summary</h2>
    <table class="table">
        <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">Item title</th>
            <th scope="col">Price</th>
            <th scope="col">Quantity</th>
            <th scope="col">Total Item Price</th>
        </tr>
        </thead>
        <tbody>
        {% for order_item in object.items.all %}
        <tr>
            <th scope="row">{{ forloop.counter }}</th>
            <td>{{ order_item.item.product_title }}</td>
            <td>{{ order_item.item.sale_price }}</td>
            <td>
                <a href=""><i class="fas fa-minus mr-2"></i></a>
                {{ order_item.quantity }}
                <a href="{% url 'core:add-to-cart' order_item.item.slug %}"><i class="fas fa-plus ml-2"></i></a>
            </td>
            <td>
            {% if order_item.item.discount %}
                ${{ order_item.get_total_discount_item_price }}
                <span class="badge badge-primary">Saving ${{ order_item.get_amount_saved }}</span>
            {% else %}
                ${{ order_item.get_total_item_price }}
            {% endif %}
            <a style='color: red;' href="{% url 'core:remove-from-cart' order_item.item.slug %}">
                <i class="fas fa-trash float-right"></i>
            </a>
            </td>
        </tr>
        {% empty %}
        <tr>
            <td colspan='5'>Your cart is empty</td>
        </tr>
        <tr>
            <td colspan="5">
            <a class='btn btn-primary float-right' href='/'>Continue shopping</a>
            </td>
        </tr>
        {% endfor %}
        <!--{% if object.coupon %}
        <tr>
            <td colspan="4"><b>Coupon</b></td>
            <td><b>-${{ object.coupon.amount }}</b></td>
        </tr>
        {% endif %}-->
        {% if object.get_total %}
        <tr>
            <td colspan="4"><b>Order Total</b></td>
            <td><b>${{ object.get_total }}</b></td>
        </tr>
        <tr>
            <td colspan="5">
            <a class='btn btn-warning float-right ml-2' href=''>Proceed to checkout</a>
            <a class='btn btn-primary float-right' href='/'>Continue shopping</a>
            </td>
        </tr>
        {% endif %}
        </tbody>
    </table>

    </div>

    </div>
  </main>

{% endblock content %}

以下是错误信息:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/onlineshopping/add-to-cart/p1/

Django Version: 3.2
Python Version: 3.9.1
Installed Applications:
['django_social_share',
 'django_pgviews',
 'demo',
 'product',
 'signup',
 'signin',
 'home',
 'bmedia',
 'affiliation',
 'pyshorteners',
 'onlineshopping',
 'celery',
 'django_tables2',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\blink\myblink\onlineshopping\views.py", line 124, in add_to_cart
    order_item = OrderItems.objects.get(
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 431, in get
    num = len(clone)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 262, in __len__
    self._fetch_all()
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1156, in execute_sql
    sql, params = self.as_sql()
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 522, in as_sql
    where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 439, in compile
    sql, params = node.as_sql(self, self.connection)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\where.py", line 81, in as_sql
    sql, params = compiler.compile(child)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 439, in compile
    sql, params = node.as_sql(self, self.connection)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_lookups.py", line 132, in as_sql
    return super().as_sql(compiler, connection)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\lookups.py", line 315, in as_sql
    return super().as_sql(compiler, connection)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\lookups.py", line 194, in as_sql
    rhs_sql, rhs_params = self.process_rhs(compiler, connection)
  File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\lookups.py", line 297, in process_rhs
    raise ValueError(

Exception Type: ValueError at /onlineshopping/add-to-cart/p1/
Exception Value: The QuerySet value for an exact lookup must be limited to one result using slicing.

【问题讨论】:

  • 能否在问题中添加错误信息?
  • @allexiusw 我已经添加了错误信息。

标签: python django django-models django-queryset


【解决方案1】:

问题是因为这个sn-p:

    item = AffProduct.objects.filter(slug=slug)
    order_item = OrderItem.objects.get(
        item=item,
        user=request.user,
        ordered=False
    ) 

您正在通过OrderItemitem 字段和AffProduct 查询集进行过滤。但是,您只能使用一个实例,因此会出现错误。

如果slug 是唯一的,请改用get

item = AffProduct.objects.get(slug=slug)

如果它不是唯一的,请添加一种方法来确定具有相同 slug 的 AffProducts 中的哪一个将用作 item

【讨论】:

  • slug 在名为 p1、p2、p3.. 的数据库中是唯一的。我尝试使用这个逻辑。它说返回了多个对象,因此,get() 返回了多个 AffProduct——它返回了 11!
  • 这实际上意味着它不是唯一的。在这种情况下,您需要添加一种方法来确定将使用哪个具有相同 slug 的 AffProducts。
  • 实际上,当我为AffProduct创建一个slug字段时,所有的slug都被命名为p1,我将它重命名为p1、p2等等
  • 我添加了错误信息,请帮帮我
  • Multiple Objects Returned, Hence, get() returned more than one AffProduct -- it returned 11! -- 你通过的 slug 是什么?那个蛞蝓返回 11 AffProducts
【解决方案2】:

正如@bdbd 在他的回答中提到的那样,您正在使用get() 方法,该方法只需要过滤一项不多,不少,无论您得到多于或少于一项,它都会运行以下错误:

  • 如果少于一个对象,您将收到错误AffProduct.DoesNotExist
  • 如果有多个对象,您将收到错误AffProduct.MultipleObjectsReturned

所以为了避免你必须确保对象是唯一的并且对象存在,在这种情况下你总是会得到一个对象。

但是,如果您没有像您的情况那样的唯一数据,则必须更改为以下内容:

order_item = OrderItem.objects.filter(
    item=item,
    user=request.user,
    ordered=False
)
for i in order_item:
    print(i)
else:
    print("No orders in here")

但是,如果您只想要一个订单,即使它会导致您出错,您也可以这样做:

order_item = OrderItem.objects.filter(
    item=item,
    user=request.user,
    ordered=False
)
order = order_item.first()
if order is not None:
   print(order)
else:
   print('There are not orders in here')

【讨论】:

  • 我在管理表中遇到编程错误,说 relation "onlineshopping_orderitem" does not exist,当我运行 migrate 时,没有任何更改或任何迁移正在应用。在 Django admin 中,我可以看到该表,但是当我尝试打开时说,Programmin Error,而在 POSTGRESQL 中,没有创建这样的表。
  • 这与您的问题无关。考虑为此提出一个新问题。
猜你喜欢
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
  • 2020-11-13
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
相关资源
最近更新 更多