django rest framework foreign key relation giving error in serializer
# models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
# Other Author fields...
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
# Other Book fields...
# serializers.py
from rest_framework import serializers
from .models import Author, Book
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ['id', 'name']
class BookSerializer(serializers.ModelSerializer):
author = AuthorSerializer() # Foreign key serialization
class Meta:
model = Book
fields = ['id', 'title', 'author']
This Django code demonstrates a simple scenario involving two models, Author
and Book
, with a foreign key relationship. The Author
model represents an author's details, while the Book
model represents a book with a foreign key (author
) referencing the Author
model.
In models.py
, the Author
model has a name field, and the Book
model has a title field along with a foreign key field referencing the Author
model using models.ForeignKey
.
In serializers.py
, the Django REST Framework serializers are used to convert complex data types (like querysets and model instances) into native Python data types that can be easily rendered into JSON/XML content.
AuthorSerializer
is created using theModelSerializer
class from Django REST Framework. It includes fieldsid
andname
from theAuthor
model.BookSerializer
includes theauthor
field, which usesAuthorSerializer()
to represent the related author in a nested structure when serializing aBook
instance. This enables showing author details within the book serializer.
This setup allows for serialization of Book
instances with nested author details, making it easier to represent complex relationships in the API responses.