UserCheckout匹配查询不存在



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

订单/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)

订单/mixins.py

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

订单/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)

相关内容

  • 没有找到相关文章

最新更新