一次创建两个嵌套模型的Api端点

时间:2019-05-25 17:33:53

标签: django django-rest-framework

我正在创建Django API应用程序,我有三个主要应用程序(发布,异常,事件),用户可以创建异常或事件(女巫是发布的嵌套模型)。

我目前所做的只是使用generic viewsmixins,因此我可以列出create update并为他自己删除每个模型,但是现在我想通过一个请求创建一个异常或事件(不是创建帖子,然后创建活动)。

发布模型

class Post(models.Model):
    post_owner = models.ForeignKey(MyUser, on_delete=models.CASCADE)
    description = models.TextField(max_length=255)
    city = models.ForeignKey(City, related_name='location', on_delete=models.CASCADE)
    longitude = models.CharField(max_length=255)
    latitude = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

后序列化程序

class PostSerializer(serializers.ModelSerializer):
    comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    reactions = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Post
        fields = '__all__'

发布ApiViews

class PostAPIView(mixins.CreateModelMixin, generics.ListAPIView):
    lookup_field = 'pk'
    serializer_class = PostSerializer

    def get_queryset(self):
        qs = Post.objects.all()
        return qs

    def perform_create(self, serializer):
        serializer.save(post_owner=self.request.user)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def get_serializer_context(self, *args, **kwargs):
        return {"request": self.request}


class PostRudView(generics.RetrieveUpdateDestroyAPIView):
    lookup_field = 'pk'
    queryset = Post.objects.all()
    serializer_class = PostSerializer

事件模型

class Event(models.Model):
    post = models.ForeignKey(Post, related_name='event', on_delete=models.CASCADE)
    approved_by = models.ForeignKey(MyUser, related_name='approvedBy', on_delete=models.CASCADE, null=True)
    approved_at = models.DateTimeField(null=True)
    max_participants = models.IntegerField()
    starts_at = models.DateTimeField()

事件序列化器

class EventSerializer(serializers.ModelSerializer):

    class Meta:
        model = Event
        fields = '__all__'

事件ApiViews

class EventAPIView(mixins.CreateModelMixin, generics.ListAPIView):
    lookup_field = 'pk'
    serializer_class = EventSerializer

    def get_queryset(self):
        qs = Event.objects.all()
        return qs

    def perform_create(self, serializer):
        serializer.save()

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def get_serializer_context(self, *args, **kwargs):
        return {"request": self.request}


class EventRudView(generics.RetrieveUpdateDestroyAPIView):
    lookup_field = 'pk'
    queryset = Event.objects.all()
    serializer_class = EventSerializer

0 个答案:

没有答案