Aashay Amballi
Aashay Amballi

Reputation: 1411

How to serialize the annotate and foreign key in DRF

I have 2 Django models that consider the below sample models.

class Status(models.Model):
    name = models.CharField(max_length=50)

class Resolution(models.Model):
    resolution_status = models.ForiegnKey(Status)
    resolver_name = models.CharField(max_length="50")

So what I want to do is get the count of distinct status from the Resolution model.

so for that, I've written an ORM which looks like this.

status_count = Resolution.objects.values('resolution_status').annotate(status_count=Count(
                'resolution_status'))

so from the above ORM, I will fetch the distinct resolution_status with its count from the Resolution model.

so the main question is here is now I want to serialize the queryset into JSON. so for that, I've written the serializer class like this.

class CountSerializer(serializers.ModelSerializer):
    status_count = serializers.IntegerField()
    resolution_status = serializers.CharField(source="resolution_status")

class Meta:
    model = Resolution
    fields = ["resolution_status", "status_count"]

From the above serializer class, I'm getting the JSON output like this

enter image description here

Instead of showing the ID of that particular status, I want to display the name.

for example it should look like this.

[
    {
        resolution_status: "Status Name", count: 100
    },
    {
        resolution_status: "Status Name 1", count: 120
    },
    {
        resolution_status: "Status Name 3", count: 80
    },
    {
        resolution_status: "Status Name 4", count: 10
    }
]

I googled a lot and went through a few StackOverflow QA but couldn't able to figure out why it's not adding the status name. Please anyone help me with this.

Upvotes: 0

Views: 1458

Answers (1)

Aashay Amballi
Aashay Amballi

Reputation: 1411

So I figured out the answer to this.

I had to rewrite the queryset for this the queryset would look like this.

status_count = Resolution.objects.values('resolution_status').annotate(status_count=Count(
            'resolution_status')).values('resolution_status__name', 'status_count')

and after this, I had to change the model serializer class field to this

class CountSerializer(serializers.ModelSerializer):
    status_count = serializers.IntegerField()
    resolution_status = serializers.CharField(source="resolution_status__name")

    class Meta:
        model = Resolution
        fields = ["resolution_status", "status_count"]

After changing this I was able to get the desired output. I'm not sure this is the best answer, but if anybody able to find out the better answer then please let me know.

Upvotes: 3

Related Questions