【问题标题】:Selecting children from a parent row with a very specific ruleset使用非常具体的规则集从父行中选择子代
【发布时间】:2019-03-08 05:59:41
【问题描述】:

我有一个父模型,它有 30,000 多条记录,每条记录至少有 3-4 个子代。我希望能够在具有非常特定规则集的桌子上显示孩子。

from django.db import models
from django.utils.translation import ugettext_lazy as _

class Parent(models.Model):
    name = models.CharField(_("Name"), max_length=128)    


class Child(models.Model):
    parent = models.ForeignKey(Parent)
    state = models.CharField(
        _("State"), choices=(
            ('A', "Apple"),
            ('B', "Ball"),
            ('C', "Cat"),
            ('D', "Dog"),
        )
    )

使用上面的两个模型,我过滤掉了所有state is "A" or "B" 的子对象。我发现很难满足的部分要求是,我可能在AsCs 之间有一些Bs,例如,排列成一排:

 [R]        [R]         [R]
Apple       Cat         Cat

如果它们之间没有 B 状态,我想检索 AsCs 但我有一个特殊情况,我想在下一个 C 之前检索最新的 B 而不是AB 自己。

            [R]                                 [R]                     [R]         [R]
Apple       Ball        Cat         Ball        Ball        Cat         Ball        Cat

总结:

如果在 As 或 Cs 之后有 B,或者行尾是 B,我希望始终在下一个 C 之前选择最新的 B。

这完全可以用 PostgreSQL 吗?由于缺少查询所有内容并使用 Python 按摩数据,因为我显示记录的表是分页的。

【问题讨论】:

  • 如果您代表树木,您可能会对MPTTTreebeard 感兴趣
  • @PauloScardine 实际上,如果它是一个 Ball,则使用 MPTT 总是选择它之前的对象作为父对象。这有帮助,谢谢!

标签: django postgresql django-models orm


【解决方案1】:

@PauloScardine 有一个好主意,如果它是一个 Ball,则使用 MPTT 始终选择它之前的对象作为父对象。谢谢!

【讨论】:

  • 酷,谢谢分享。它肯定会帮助同一条船上的人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 2016-09-18
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多