hpw to create related model in django rest framework logic

To create a related model in Django Rest Framework, follow these steps:

  1. Define the models: Start by defining the models that you want to relate. For example, let's say we have a Book model and a Author model. The Book model has a foreign key relationship with the Author model.
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    # other fields

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    # other fields
  1. Create the serializers: Next, create serializers for the models. Serializers define how the data will be converted to and from JSON format. In this case, we need to create a serializer for both the Author and Book models.
from rest_framework import serializers

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = '__all__'

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'
  1. Define the viewsets: Now, define the viewsets for the models. Viewsets handle the logic for different actions such as creating, retrieving, updating, and deleting the objects.
from rest_framework import viewsets

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
  1. Configure the URLs: Finally, configure the URLs for the viewsets in your urls.py file. This maps the viewsets to specific endpoints.
from django.urls import path, include
from rest_framework import routers

router = routers.DefaultRouter()
router.register('authors', AuthorViewSet)
router.register('books', BookViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

With these steps, you have created a related model in Django Rest Framework. The Book model has a foreign key relationship with the Author model, and you can perform CRUD operations on both models through the defined API endpoints.