Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. It is built on top of Django, a popular web framework for Python. DRF provides a number of features that make it easy to build APIs, including:
- Serialization: DRF provides a number of sterilizers that can be used to convert Django models to and from JSON, XML, and other formats.
- Authentication: DRF provides a number of authentication mechanisms, including Basic AUTH, OAuth, and JWT.
- Authorization: DRF provides a number of authorization mechanisms, including Django's built-in permissions and custom permissions.
- Testing: DRF provides a number of tools for testing APIs, including a built-in API browser and a test client.
Many to many relationship in django model
- Define the serializer for the model with the many-to-many field. The serializer should include a field for the many-to-many field. For example, if the model is called Movie and the many-to-many field is called genres, the serializer would look like this:
class MovieSerializer(serializers.ModelSerializer): genres = serializers.ManyRelatedField(queryset=Genre.objects.all())
- Define the viewset for the model. The viewset should include an action for adding data to the many-to-many field. For example, the following viewset would allow users to add genres to movies:
class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() @action(detail=True, methods=['POST']) def add_genres(self, request, pk=None): movie = self.get_object() genres = request.data.get('genres') for genre in genres: movie.genres.add(genre) return Response(status=status.HTTP_200_OK)
- Register the viewset with the API. To register the viewset with the API, add the following code to your urls.py file:
from django.urls import path from .views import MovieViewSet urlpatterns = [ path('movies/', MovieViewSet.as_view()), ]
0 Comments