python - 无法从 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 也可以正常工作,因为可以获取其他数据。
解决方案
如果可以的话,为了便于人们给出答案,请以可读格式添加您的代码。
这是你的代码:
楷模:
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 >
希望有帮助。祝你好运
推荐阅读
- planning - PDDL - 使用solver.planning.domains 使用数字流利
- ruby - 将网站集从页面传递到布局 jekyll
- asp.net - 使用 msal.js 调用 web api 但在 asp.net webform 中失败
- jenkins - 神器jenkins插件的构建保留策略不会删除柯南包的所有文件
- node.js - NODE JS - 客户端网络套接字在建立安全 TLS 连接之前断开
- javascript - axios没有编译
- javascript - React js:我需要在 chrome 浏览器中打开文件而不是下载。例如:onclick docx、excel、pdf、zip 文件在推荐的应用程序中打开
- azure-devops - 在 Devops Azure 工作项中添加或修改工作流原因
- ios - 在展开可选值时意外发现 nil»错误
- sql - 将 SQL 脚本转换为 Tableau 计算表