python - DRF无法发布传递主键的数据

时间:2017-03-15 18:41:38

标签: python django django-rest-framework

我开始使用Django并且我遵循了Django Rest Framework网站上提供的教程,现在我正在尝试调整教程以做一些更复杂的事情。

我试图创建一个" Like"社交网络系统。用户可以创建帖子(UserPosts)和其他用户的帖子。

我以这种方式创建新的UserPosts(使用命令行):

http -a admin:Pass1234 POST http://127.0.0.1:8000/posts/ description="I'm just a random comment"

一切正常。 问题是当我尝试创建一个Like实例时。在这种情况下,我需要传递一个UserPost ID,所以我和我一样做了一个新的评论:

http -a admin:Pass1234 POST http://127.0.0.1:8000/likes/ post="1"

但是当我这样做时,我收到以下错误:

"post": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got unicode."
        ]
    }

模型如下:

class UserPost(models.Model):
    owner = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    description = models.CharField(max_length=100, blank=True, default='')

    def save(self, *args, **kwargs):
        options = self.description and {'description': self.description} or {}
        super(UserPost, self).save(*args, **kwargs)

    class Meta:
        ordering = ('timestamp',)


class Like(models.Model):
    owner = models.ForeignKey('auth.User', related_name='likes', on_delete=models.CASCADE)
    post = models.ForeignKey(UserPost, related_name='likes', on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        options = self.post and {'post': self.post}
        super(Like, self).save(*args, **kwargs)

    class Meta:
        ordering = ('timestamp',)

序列化器:

class UserPostSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.id')

    class Meta:
        model = UserPost
        fields = ('url', 'id', 'description', 'owner', 'timestamp')


class LikeSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.id')
    post = UserPostSerializer(source='post')

    class Meta:
        model = Like
        fields = ('id', 'owner', 'post', 'timestamp')

观点:

class PostViewSet(viewsets.ModelViewSet):
    queryset = UserPost.objects.all()
    serializer_class = UserPostSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

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


class LikeViewSet(viewsets.ModelViewSet):
    queryset = Like.objects.all()
    serializer_class = LikeSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)

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

路由器和网址:

router = DefaultRouter()
router.register(r'posts', views.PostViewSet)
router.register(r'users', views.UserViewSet)
router.register(r'likes', views.LikeViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

知道发生了什么事吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要从post = UserPostSerializer

中删除LikeSerializer
class LikeSerializer(serializers.ModelSerializer):
  owner = serializers.ReadOnlyField(source='owner.id')

  class Meta:
    model = Like
    fields = ('id', 'owner', 'post', 'timestamp')

以便django-rest-framework对相关的UserPost使用PrimaryKeyRelatedField(这是与ModelSerializer相关模型的默认值)。
然后,您可以使用post="1"作为参数创建您喜欢的条目。