Django 查询选择具有非零子级的父级
我的模型本身带有外键,如下所示:
class Concept(models.Model):
name = models.CharField(max_length=200)
category = models.ForeignKey('self')
但我无法弄清楚如何选择具有非零子值的所有概念。这可以通过 django QuerySet API 实现吗?或者我必须编写自定义 SQL?
I have model with a Foreign Key to itself like this:
class Concept(models.Model):
name = models.CharField(max_length=200)
category = models.ForeignKey('self')
But I can't figure out how I can select all concepts that have nonzero children value. Is this possible with django QuerySet API or I must write custom SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解正确的话,每个
Concept
可能有另一个Concept
作为父级,并且它被设置到category
字段中。换句话说,至少有一个子概念的
Concept
将在category
字段中至少被引用一次。一般来说,这在 Django 中并不容易实现;但是,如果您没有太多类别,您可以考虑类似
SELECT * FROM CONCEPTS WHERE CONCEPTS.ID IN (SELECT CATEGORY FROM CONCEPTS);
的查询 - 这是您可以做的事情使用 Django 轻松映射:请注意,如 Django 文档,该查询在某些数据库上可能存在性能问题;因此,您应该将其作为列表:
但请注意,这可能会遇到某些数据库限制 - 例如,Oracle 允许此类列表中最多包含 1000 个元素。
If I understand it correctly, each
Concept
may have anotherConcept
as parent, and this is set into thecategory
field.In other words, a
Concept
with at least a child will be referenced at least once in thecategory
field.Generally speaking, this is not really easy to get in Django; however if you do not have too many categories, you can think for a query of the like of
SELECT * FROM CONCEPTS WHERE CONCEPTS.ID IN (SELECT CATEGORY FROM CONCEPTS);
- and this is something you can map easily with Django:Note that, as stated on Django documentation, this query may have performance issues on certain databases; therefore you should instead put it as a list:
But please be aware that this could hit some database limitation -- for instance, Oracle allows up to 1000 elements in such lists.
像这样的事情怎么样:
How about something like this:
您在那里编写的方式将需要
category
的值。修复该问题后(在字段构造函数中使用null=True
),请使用以下命令:The way you have it written there will require a value for
category
. Once you have fixed that (withnull=True
in the field constructor), use this: