简体   繁体   中英

Django add aggregate operation to a query result

I'm trying to do an aggregate operation between two tables using Django, my models are:

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'

The query that I'm trying to build is:

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

I'm trying to generate a model, to store the information of those tables in a single one query, but anything works. Someone has an idea about how to do it?

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 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM