django rest framework many to many serialize and apiview

时间:2017-04-06 16:56:10

标签: django-rest-framework

I am creating APIView for book list and add, delete. Is this serialization the right way? I want to show a list of books, but I do not know what to put in '?'.

member/models.py

class MyUser(AbstractBaseUser, PermissionsMixin):
    username = models.EmailField(unique=True, max_length=256)
    nickname = models.CharField(max_length=256)
    is_staff = models.BooleanField(default=False)
    created_date = models.DateTimeField(auto_now_add=True)
    mybook = models.ManyToManyField(Book)

book/models.py

from django.db import models


class Book(models.Model):
    title = models.CharField(max_length=256)
    author = models.CharField(max_length=200)

    def __str__(self):
        return self.title

book/seralizers.py

from rest_framework import serializers

from book.models import Book


class MyBookSerializer(serializers.ModelSerializer):
    mybook = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Book
        fields = (
            'title',
            'author',
    )

apiview.py

class MyBook(APIView):

    def get(self, request):
        mybook = Book.objects.filter(myuser=?)
        serializer = MyBookSerializer(mybook)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request):
        pass

    def delete(self, request):
        pass

1 个答案:

答案 0 :(得分:0)

如果您想为模型创建CRUD,取决于request.user,您只需使用ModelViewSet

from rest_framework import viewsets

class MyBookViewSet(viewsets.ModelViewSet):
    serializer_class = MyBookSerializer

    def get_queryset(self, request):
        return Book.objects.filter(myuser=self.request.user)

这一切都是为了观看。您只需要为视图集指定路由器 urls.py:

from rest_framework import routers

router = routers.DefaultRouter()

router.register('books', MyBookViewSet)
urlpatterns = []
urlpatterns += router.urls  

将此usl文件包含在根网址中,您就完成了 如果要使用related_name名称,还需要为m2m字段指定myuser
 mybook = models.ManyToManyField(Book, related_name='myuser')
而且你不需要在序列化器中使用这个字段:
mybook = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
viewsets docs
routers docs