0

I am having trouble in showing cross relation data in my api end-point

this is my serlization class:

class ArticleSerializer(serializers.ModelSerializer):
    # these two variables are assigned coz, author and category are foregin key
    author = serializers.StringRelatedField()
    category = serializers.StringRelatedField()

    class Meta:
        model =  Article
        fields = '__all__'

Above serialization working fine but not satisfy needs.

And this is my models

from django.db import models
import uuid

class Organization(models.Model):
    organization_name = models.CharField(max_length=50)
    contact = models.CharField(max_length=12, unique=True)

    def __str__(self):
        return self.organization_name

class Author(models.Model):
    name = models.CharField(max_length=40)
    detail = models.TextField()
    organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Article(models.Model):
    alias = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author')
    title = models.CharField(max_length=200)
    body = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

this is my views:

class ArticleSingle(RetrieveAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    lookup_field = 'alias'

and currently my end-point showing like these but i dont like it:

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "alias": "029a4b50-2e9a-4d35-afc6-f354d2169c05",
    "author": "jhon doe",
    "category": "sic-fi",
    "title": "title goes here",
    "body": "this is body"
}

I want the end-point should show the data with author details like, author, organization_name, contact, etc if you dont understand it, please see my models how i designe it.

The end-point should show each and every related data that with foreign key, i hope you got my issue, thanks for your time

1 Answers1

0

What you are looking for is nested serialization.

Rather than specifying author and category as StringRelatedFields, you should assign them as serializer classes (the same applies to the Organization model):

class OrganizationSerializer(serializers.ModelSerializer):
    ...

    class Meta:
        model = Organization
        fields = '__all__'


class AuthorSerializer(serializers.ModelSerializer):
    organization = OrganizationSerializer()
    ...

    class Meta:
        model = Author
        fields = '__all__'


class CategorySerializer(serializers.ModelSerializer):
    ...

    class Meta:
        model = Category
        fields = '__all__'


class ArticleSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()
    category = CategorySerializer()

    class Meta:
        model =  Article
        fields = '__all__'

This mechanism will serialize your data as you desire:

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "alias": "029a4b50-2e9a-4d35-afc6-f354d2169c05",
    "author": {
        "name": "jhon doe",
        "organization": {
            "organization_name": "..."
        }
        ...
    }
    "category": {
         "name": "sic-fi"
    }
    "title": "title goes here",
    "body": "this is body"
}

Note: If you want to perform POST requests for creation of those resources, you can find some useful information here.

wencakisa
  • 5,850
  • 2
  • 15
  • 36