首页 > 解决方案 > 无法从 DJango 中的数据库中过滤

问题描述

这是我的models.py:

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    date_ordered = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False)
    transaction_id = models.CharField(max_length=100, null=True)

这是我的view.py:

def customer_dashboard(request,id):
    order = Order.objects.filter(customer=id)
    print(order)
    return render(request, 'accounts/customer_dashboard.html', {'user':user, 'customer':customer})

我试图打印结果,我得到了这个

<QuerySet []>

但我非常确定数据在数据库中可用,url 也可以正常工作,因为可以获取其他数据。

标签: pythondjango

解决方案


如果可以的话,为了便于人们给出答案,请以可读格式添加您的代码。

这是你的代码:

楷模:

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) 
    date_ordered = models.DateTimeField(auto_now_add=True) 
    complete = models.BooleanField(default=False) 
    transaction_id = models.CharField(max_length=100, null=True)

意见:

def customer_dashboard(request,id):
    order = Order.objects.filter(customer=id) 
    print(order) 
    return render(request, 'accounts/customer_dashboard.html', {'user':user, 'customer':customer})

首先:您的上下文都与您的查询集无关

根据您的观点,上下文应该是“订单”,

return render(request, 'accounts/customer_dashboard.html', {'order':order})

第二:您按 id 查询设置过滤器,虽然您确实提到了整个消费者,但我假设您的消费者是现在正在订购的用户,所以您可能已经注册了用户,您可以这样做:

order = Order.objects.get(id=order_id, customer=request.user)

因此:

def customer_dashboard(request,order_id):
    order = Order.objects.get(id=order_id, customer=request.user)
    print(order) 
    return render(request, 'accounts/customer_dashboard.html', {'order':order})

order_id 将在该视图的 url 中,如 <int:order_id >

希望有帮助。祝你好运


推荐阅读