UserCheckout 匹配查询不存在

UserCheckout matching query does not exist

我正在尝试显示与每个登录用户匹配的所有订单,我不明白为什么它在尝试过滤用户时给我带来问题,因为它告诉我 UserCheckout 没有任何匹配的查询:

orders/views.py

class OrderList(LoginRequiredMixin, ListView):

    queryset = Order.objects.all()

    def get_queryset(self):
        
        user_check_id = self.request.user.id
        user_checkout = UserCheckout.objects.get(id=user_check_id)  
        return super(OrderList, self).get_queryset().filter(user=user_checkout)

orders/mixins.py

class LoginRequiredMixin(object):

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(LoginRequiredMixin, self).dispatch(request,*args, **kwargs)

orders/models.py

class UserCheckout(models.Model):
            user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete = models.CASCADE) # not required as to allow guests to checkout too
            email = models.EmailField(unique=True) # required, unique as if there the guest already has an authentication just one email needed
        
        
            def __str__(self):
                return self.email
    
class Order(models.Model):
        status                  = models.CharField(max_length=120, choices=ORDER_STATUS_CHOICES, default='created')
        cart                    = models.ForeignKey(Cart, on_delete=models.CASCADE)
        user                    = models.ForeignKey(UserCheckout, null=True, on_delete=models.CASCADE)
        billing_address         = models.ForeignKey(UserAddress, related_name='billing_address', null=True,on_delete=models.CASCADE)
        shipping_address        = models.ForeignKey(UserAddress, related_name='shipping_address', null=True, on_delete=models.CASCADE)
        shipping_total_price    = models.DecimalField(max_digits=50, decimal_places=2, default=5.99)
        order_total             = models.DecimalField(max_digits=50, decimal_places=2)
    
        def __str__(self):
            return str(self.cart.id)

它给我的错误:

   DoesNotExist at /orders/
UserCheckout matching query does not exist.

您正在尝试使用 User's 主键 (id) 作为 UserCheckout's 主键,即行:

user_check_id = self.request.user.id
user_checkout = UserCheckout.objects.get(id=user_check_id)

将这些行更改为:

user = self.request.user
user_checkout = UserCheckout.objects.get(user=user)

如果 UserCheckout 实例不存在,这也会抛出异常,您可以使用 try-except 或使用 django 的快捷函数 get_object_or_404:

from django.shortcuts import get_object_or_404

user_checkout = get_object_or_404(UserCheckout, user=user)