如何在Django中以ORM样式实现这个复杂的查询?

时间:2017-11-24 14:28:04

标签: django

我有一个复杂的查询,可以帮助我创建一个在列表视图中显示的丰富数据集。查询的结果包括来自事件模型的字段和基于子查询中的聚合的字段。

我想知道如何使用Django ORM实现这一点,而不是一直编写原始查询?

以下示例查询:

SELECT g.event_id,event_name, gm.member_counts 
    from care_event g 
    inner join (
      SELECT gc.event_id, COUNT(DISTINCT gc.member_id) AS member_counts FROM event_member gc
      INNER JOIN care_member m on gc.member_id = m.member_id and m.is_deleted = 'N'
      GROUP BY 1
    ) gm ON g.event_id = gm.event_id

    WHERE org_id = %(org_id)s AND g.is_deleted = 'N'  

Event,Member和EventMember是存储数据的模型。

[更新]以下添加的模式代码:

class Member(models.Model):

    member_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    member_name = models.CharField(max_length=100, blank=True, null=True)
    is_deleted = models.CharField(max_length=1, default='N')

    class Meta:
        db_table = 'care_member'


class Event(models.Model):

    event_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    org_id = models.ForeignKey(Organisation, on_delete=models.CASCADE)
    event_name = models.CharField(max_length=100, blank=True, null=False)
    members = models.ManyToManyField(Member, through='EventMember')
    is_deleted = models.CharField(max_length=1, default='N', null=False)

    class Meta:
        db_table = 'care_event'


class EventMember(models.Model):

    # DB auto generated 'id' field is the PK.
    event_id = models.ForeignKey(Event, on_delete=models.CASCADE)
    member_id = models.ForeignKey(Member, on_delete=models.CASCADE)

    class Meta:
        db_table = 'event_member'

我可以在ORM样式中实现此查询的概念级别实现吗?感谢。

0 个答案:

没有答案