Django 查询选择具有非零子级的父级

发布于 2024-08-28 09:21:02 字数 240 浏览 9 评论 0原文

我的模型本身带有外键,如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

作妖 2024-09-04 09:21:02

如果我理解正确的话,每个 Concept 可能有另一个 Concept 作为父级,并且它被设置到 category 字段中。
换句话说,至少有一个子概念的Concept将在category字段中至少被引用一次。

一般来说,这在 Django 中并不容易实现;但是,如果您没有太多类别,您可以考虑类似 SELECT * FROM CONCEPTS WHERE CONCEPTS.ID IN (SELECT CATEGORY FROM CONCEPTS); 的查询 - 这是您可以做的事情使用 Django 轻松映射:

Concept.objects.filter(pk__in=Concept.objects.all().values('category'))

请注意,如 Django 文档,该查询在某些数据库上可能存在性能问题;因此,您应该将其作为列表:

Concept.objects.filter(id__in=list(Concept.objects.all().values('category')))

但请注意,这可能会遇到某些数据库限制 - 例如,Oracle 允许此类列表中最多包含 1000 个元素。

If I understand it correctly, each Concept may have another Concept as parent, and this is set into the category field.
In other words, a Concept with at least a child will be referenced at least once in the category 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:

Concept.objects.filter(pk__in=Concept.objects.all().values('category'))

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:

Concept.objects.filter(id__in=list(Concept.objects.all().values('category')))

But please be aware that this could hit some database limitation -- for instance, Oracle allows up to 1000 elements in such lists.

墟烟 2024-09-04 09:21:02

像这样的事情怎么样:

concepts = Concept.objects.exclude(category=None)

How about something like this:

concepts = Concept.objects.exclude(category=None)
小伙你站住 2024-09-04 09:21:02

您在那里编写的方式将需要 category 的值。修复该问题后(在字段构造函数中使用 null=True),请使用以下命令:

Concept.objects.filter(category__isnull=False)

The way you have it written there will require a value for category. Once you have fixed that (with null=True in the field constructor), use this:

Concept.objects.filter(category__isnull=False)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文