首页 > 解决方案 > 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)

即使该查询不正确。

我希望有一个人可以帮助我。

谢谢

标签: pythondjangodatabasefilteringrelationship

解决方案


推荐阅读