'Serializing reverse relationship of a ForeignKey with a DRF ModelSerializer

I'm trying to generate a data structure following this sample:

[
  {
    "name": "groupname",
    "key": "grouping1",
    "base_templates": [
      {
        "identity": "123456",
        "name": "createxxx"
      },
      {
        "identity": "112233",
        "name": "deletexxx"
      }
    ]
  },
  {
    "name": "groupname2",
    "key": "grouping2",
    "base_templates": [
      {
        "identity": "123999999",
        "name": "runxxxx"
      }
    ]
  }
]

These are the models I'm using:

class TicketCategory(Model.models):
    name = models.CharField(verbose_name="name", max_length=100, unique=True)
    key = models.CharField(verbose_name="key", max_length=100, unique=True)


class BaseTemplate(Model.models):
    identity = models.UUIDField(verbose_name="tag", default=uuid.uuid4, editable=False)
    category = models.ForeignKey(
        TicketCategory, verbose_name="grouping", on_delete=models.CASCADE
    )
    name = models.CharField(
        verbose_name="name", max_length=100, default="", db_index=True
    )

The serializers and the view I am trying to use:

class BaseTemplateSerializer(serializers.ModelSerializer):
    class Meta:
        model = BaseTemplate
        fields = "__all__"


class TicketCategoryDashboardSerializer(serializers.ModelSerializer):
    basetmplate = BaseTemplateSerializer()

    class Meta:
        model = TicketCategory
        fields = "__all__"


class TicketCategoryDashboard(APIView):

    def get(self, request: Request):
        r = TicketCategory.objects.all().last()
        serializer = TicketCategoryDashboardSerializer(r)
        return Response(serializer.data, status=200)

How can I generate the serialized data in that sample structure I have provided? I'm having trouble to generate that structure with the reverse side of the model relationship.



Solution 1:[1]

I'd suggest adding a related_name="base_templates" to your category = models.ForeignKey(...), and then you can define your serializer as:

class TicketCategoryDashboardSerializer(serializers.ModelSerializer):
    base_templates = BaseTemplateSerializer(many=True)

    class Meta:
        model = TicketCategory
        fields = "__all__"

The Django documentation has examples on it as well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 henriquesalvaro