【发布时间】: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" 的子对象。我发现很难满足的部分要求是,我可能在As 和Cs 之间有一些Bs,例如,排列成一排:
[R] [R] [R]
Apple Cat Cat
如果它们之间没有 B 状态,我想检索 As 和 Cs 但我有一个特殊情况,我想在下一个 C 之前检索最新的 B 而不是A 或 B 自己。
[R] [R] [R] [R]
Apple Ball Cat Ball Ball Cat Ball Cat
总结:
如果在 As 或 Cs 之后有 B,或者行尾是 B,我希望始终在下一个 C 之前选择最新的 B。
这完全可以用 PostgreSQL 吗?由于缺少查询所有内容并使用 Python 按摩数据,因为我显示记录的表是分页的。
【问题讨论】:
标签: django postgresql django-models orm