manyToMany with django rest framework

2020-03-23 04:29发布

问题:

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 tag model. Here is the code for models

class ActivityType(models.Model):
    title = models.CharField(max_length=200)
    slug = models.CharField(max_length=250,unique=True)

    def __unicode__(self):
        return self.slug        

class Activity(models.Model):
    owner = models.ForeignKey('auth.user')
    title = models.CharField(max_length=200)
    slug = models.CharField(max_length=250,unique=True)
    description = models.TextField()
    tags = models.ManyToManyField(ActivityType)
    created = models.DateTimeField(auto_now_add=True, blank=True)

    def __unicode__(self):
        return self.slug

What i want to know is what is the best method to integrate DRF with the same, if possible without writing all CRUD operations from scratch.

回答1:

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')),

 )