manyToMany用django休息框架

时间:2016-06-15 07:07:40

标签: django django-rest-framework

我目前正在使用django-rest-framework提供的默认CRUD操作。它适用于普通模型,但我的模型之一与另一个标签模型有许多关系。这是模型的代码

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

我想知道的是,如果可能的话,将DRF与其相同的最佳方法是什么,而无需从头开始编写所有CRUD操作。

1 个答案:

答案 0 :(得分:5)

在你的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')
你的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

并在你的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)

还要确保按照文档

中的说明包含restframework网址
 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')),

 )