python - python - Django ORM 使用过滤的子模型检索父模型
问题描述
我在 Django 中有以下模型:
class Gasto(models.Model):
monto = models.DecimalField(default=0,decimal_places=2, max_digits=10)
nombre = models.CharField(max_length=30)
informacion = models.TextField(blank=True, default="")
numero_cuotas = models.PositiveSmallIntegerField(default=1)
es_compartido = models.BooleanField(default=False)
es_divisible = models.BooleanField(default=False)
contrato = models.ForeignKey(Contrato, on_delete=models.PROTECT)
class Cuota_Gasto(models.Model):
monto = models.DecimalField(default=0,decimal_places=2, max_digits=10)
fecha = models.DateField()
gasto = models.ForeignKey(Gasto,
related_name='cuotas',on_delete=models.DO_NOTHING)
factura_rendida = models.ForeignKey(Factura, on_delete=models.DO_NOTHING,
null=True, related_name='gasto_rendido')
factura_liquidada = models.ForeignKey(Factura,
on_delete=models.DO_NOTHING, null=True,
related_name='gasto_liquidado')
从现在开始:“Gasto”将被称为Expense,“Cuota_Gasto”将被称为Share。
Expense 是父模型,Share 是子模型,具有 1..N 的关系。
我想检索每个费用及其份额,但只检索那些满足特定条件的份额。这可能吗?
我可以通过使用related_name 和反向关系来获得所有份额的每笔费用,例如:
{
"monto": "-500.00",
"nombre": "RRR",
"informacion": "Extra",
"numero_cuotas": 1,
"es_compartido": true,
"cuotas": [
{
"id": 16,
"nombre": "RRR",
"informacion": "Extra",
"contrato": 3,
"monto": "-500.00",
"fecha": "07/07/2019",
"gasto": 4,
"factura_rendida": null,
"factura_liquidada": 12
}
]
}
但我无法访问允许我排除我不想要的共享的查询。
我在想这样的事情:
Gasto.objects.distinct().filter(cuotas__fecha__lte = date)
即使该查询不正确。
我希望有一个人可以帮助我。
谢谢
解决方案
推荐阅读
- api - 如何在 GatsbyJS 中使用 Google Analytics 插件跟踪博客文章的访问者?
- rust - “tokio::mpsc::channel”上的接收器仅在缓冲区已满时接收消息
- spring - 如何通过 GET 请求将请求正文发送到外部 API
- visual-studio-code - Shell 在 VSCode 中未正确显示
- python-3.x - 过滤下拉列表时如何修复 Plotly Dash 中的“回调错误”
- flutter - 如何使用 SharedPreferences 保存和加载对象
- python - 如何成功地在这个游戏中创建循环?
- linux - '在 raspi 上安装 wifi 模块时,没有规则来制作目标'arch/arm/tools/syscall.tbl'
- javascript - 类型错误:createDebug.load 不是函数
- node.js - 请问,我如何停止 ValidationError 的反应?