manyToMany with django rest framework

后端 未结 1 1459
遥遥无期
遥遥无期 2021-01-13 05:20

I am currently using the default CRUD operations provided by django-rest-framework. It works well with normal models but one of my model has many-many relation with another

相关标签:
1条回答
  • 2021-01-13 06:03

    In your serializers.py

    from rest_framework import serializers
    from rest_framework import generics
    
    from models import Activity
    from models import ActivityType
    
    class ActivityTypeSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = ActivityType
            fields = ('id', 'title', 'slug')
    
    class ActivitySerializer(serializers.ModelSerializer):
    
        tags = ActivityTypeSerializer(many=True, read_only=True)
    
        class Meta:
            model = Activity
            fields = ('id', 'owner', 'title', 'slug', 'description', 'tags', 'created')
    

    in your views.py

    from rest_framework import viewsets
    
    from serializers import ActivitySerializer
    from serializers import ActivityTypeSerializer
    
    from models import Activity
    from models import ActivityType
    
    class ActivityViewSet(viewsets.ModelViewSet):
        queryset = Activity.objects.all()
        serializer_class = ActivitySerializer
    
    class ActivityTypeViewSet(viewsets.ModelViewSet):
        queryset = ActivityType.objects.all()
        serializer_class = ActivityTypeSerializer
    

    and in your urls.py

    from rest_framework.urlpatterns import format_suffix_patterns
    from rest_framework import routers, serializers, viewsets
    from rest_framework import generics
    from rest_framework import viewsets, routers  
    
    from your_app.views import ActivityTypeViewSet
    from your_app.views import ActivityViewSet
    
    router = routers.DefaultRouter()
    
    router.register(r'activitytypes', ActivityTypeViewSet)  
    router.register(r'activities', ActivityViewSet)
    

    Also make sure the restframework urls are included as described in docs

     urlpatterns = patterns('',
    
     # your other urls 
    
         url(r'^api/$', include('rest_framework.urls', namespace='rest_framework')),
         url(r'api/accounts/', include('rest_framework.urls', namespace='rest_framework')),
    
     ) 
    
    0 讨论(0)
提交回复
热议问题