Django将聚合操作添加到查询结果中

时间:2017-09-28 02:09:34

标签: django django-models django-queryset

我正在尝试使用Django在两个表之间进行聚合操作,我的模型是:

class Cusinetype(models.Model):
    hometype_en = models.TextField()
    active = models.BooleanField()
    hometype_es = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'cusinetype'

class Foodpreferences(models.Model):
    id_client = models.ForeignKey(Client, models.DO_NOTHING, db_column='id_client')
    id_cusinetype = models.ForeignKey(Cusinetype, models.DO_NOTHING, db_column='id_cusinetype')
    created_at = models.DateTimeField()

    class Meta:
        managed = False
        db_table = 'foodpreferences'

我正在尝试构建的查询是:

SELECT 
    ct.id, 
    ct.hometype_en, 
    ct.hometype_es 
    , 
    ((SELECT COUNT(*) 
        FROM foodpreferences fp 
        WHERE fp.id_cusinetype = ct.id AND fp.id_client = 3    ) > 0 ) selected
FROM
    Cusinetype ct

我正在尝试生成一个模型,将这些表的信息存储在一个查询中,但任何工作都有效。 有人知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

<强> serializers.py

class PreferencesSerializer(serializers.ModelSerializer):
    selected = serializers.IntegerField()

    class Meta:
        model = Cusinetype
        fields = ('id', 'trucktype_en', 'trucktype_es', 'selected')

<强> views.py

    qs = Cusinetype.objects.filter().filter(active = True)
            qs = qs.annotate(    
                selected=Sum(Case(
                    When(foodpreferences__id_client=3, then=1),
                    output_field=IntegerField()
                ))

            )
        serializers = PreferencesSerializer(qs, many = True)
        return Response({ "result": serializers.data })