Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework - get related objects

I have these models where one book can have many contents in different languages:

class Book(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=255)

class BookContent(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    content = models.TextField()
    language = models.TextField()

--------------------Update--------------------

How should i fetch Book and its related BookContent such that the result JSON looks like the following?

{
    "results": [
        {
            "id": "d3e5185a-1b7b-427c-bbe3-030bfa2e3bce",
            "title": "My Book Title",            
            "book_content": [
                {
                    "id": "0fea8027-3ecf-4571-a95f-5a09a93408ec",
                    "content": "hello content 1",
                    "language": "english"
                },
                {
                    "id": "0fea8027-3ecf-4571-a95f-5a09a93408ed",
                    "content": "你好",
                    "language": "chinese"
                }
            ]
        }
    ]
}
like image 259
chrizonline Avatar asked Jan 30 '23 14:01

chrizonline


1 Answers

models.py
In BookContent, add related_name to foreignKey book

class Book(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=255)

class BookContent(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='content')
    content = models.TextField()
    language = models.TextField()

serializers.py
Refer here for more info

class BookContentSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookContent
        fields = ('id', 'content', 'language')

class BookSerializer(serializers.ModelSerializer):
    content = BookContentSerializer(many=True, read_only=True)

    class Meta:
        model = Book
        fields = ('id', 'title', 'content')

Result:

{
    "results": [
        {
            "id": "d3e5185a-1b7b-427c-bbe3-030bfa2e3bce",
            "title": "My Book Title",            
            "book_content": [
                {
                    "id": "0fea8027-3ecf-4571-a95f-5a09a93408ec",
                    "content": "hello content 1",
                    "language": "english"
                },
                {
                    "id": "0fea8027-3ecf-4571-a95f-5a09a93408ed",
                    "content": "你好",
                    "language": "chinese"
                }
            ]
        }
    ]
}
like image 191
chrizonline Avatar answered Feb 08 '23 16:02

chrizonline