django - 如何过滤所有子类别的查询集
问题描述
我有一个模型:
class Category(models.Model):
title = models.CharField(max_length=127)
# Lookups would be as follows:
# cat = Category.objects.get(...)
# for sub_cat in cat.sub_categories.all():
parent = models.ForeignKey(
"self",
on_delete=models.CASCADE,
related_name="sub_categories")
显然在模板中我可以过滤所有子类别:
{% for sub_cat in cat.sub_categories.all %}
我想将子类别的查询集传递给表单:
self.fields['parent'].queryset = PoliciesAndProceduresCategory.subcategories.all()
但这给出了错误:
AttributeError:类型对象“PoliciesAndProceduresCategory”没有属性“子类别”
有没有一种简单的方法来过滤这个,或者我必须做一些事情,比如定义一个Model Method
?
谢谢!
解决方案
我发现了如何:
self.fields['parent'].queryset = Category.objects.filter(parent=None)
我试过的问题是:
self.fields['parent'].queryset = Category.objects.filter(parent=False)
我把我的 JS 和 Django 搞混了!
推荐阅读
- haskell - 最外层评估策略如何评估函数的部分应用和柯里化函数的应用
- ios - 如何在 iOS 13 中获取状态栏高度?
- sql - 如何使用 Postgres SQL 将行转换为列?
- xamarin - iOS 项目中不播放视频
- java - 如何使用JAVA一次更新mongo db的单个文档中的多个字段(数组字段和普通字段)?
- python - 无法从多线程 for 循环中退出
- php - Composer 无法下载 Google Text-To-Speech 库
- graphql - 如何对 Hasura 中的 ARRAY 字段类型运行 GraphQL 过滤器查询?
- ssl - 带有 SSL 证书的 NGINX 反向代理仅在 Firefox 中给出 SEC_ERROR_UNKNOWN_ISSUER 错误
- docker - 使用 Kubernetes 文件、本地 docker 镜像和 `kubectl apply` 时如何避免 `ErrImagePull`?