Monday, July 25, 2022

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

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACp8TZhJhroy24aL38C8yJ0k1t_CdF8jNxF78yG_fY5%3DX08xEQ%40mail.gmail.com.

No comments:

Post a Comment