Queryset for get all objects with count of some of them.

18 views
Skip to first unread message

Sencer Hamarat

unread,
Jul 25, 2022, 8:16:30 AM7/25/22
to django...@googlegroups.com
Hi,

Is there a way to get all model objects, but including count of some of them within one db transaction.

Say, I have this model:

class AModel(models.Model):
    field_choices = (
        (0, "a"),
        (1, "b"),
        (2, "c")
    )

    field_one = models.CharField(max_length=32)
    field_two = models.IntegerField(coices=field_choices, default=0)

And this model has 100's of records with mixed choices.

I want to fetch all model objects bu also included count of field_choice equals "c" ones which means field_two equals to 1

Is that can be fetched by query like this?

AModel.objects.all(
).annotate(
    c_count=Count(
        Amodel.objects.filter(field_two=1).count()
    )
)



Saygılarımla,
Sencer HAMARAT

Reply all
Reply to author
Forward
0 new messages