2017-07-05 94 views
0

我想在使用Django 1.11.2的restful API中創建註釋。目前我正在從「CodingEntrepreneurs」開始講述「使用Django Rest框架的博客API」。我不知道問題是什麼。Django:`create()`沒有返回對象實例

此串行化代碼:

def create_comment_serializer(model_type='post', slug=None, parent_id=None, user=None): 
    class CommentCreateSerializer(ModelSerializer): 
     class Meta: 
      model = Comment 
      fields = [ 
       'id', 
       'content', 
       'timestamp', 
      ] 
     def __init__(self, *args, **kwargs): 
      self.model_type = model_type 
      self.slug = slug 
      self.parent_obj = None 
      if parent_id: 
       parent_qs = Comment.objects.filter(id=parent_id) 
       if parent_qs.exists() and parent_qs.count() ==1: 
        self.parent_obj = parent_qs.first() 
      return super(CommentCreateSerializer, self).__init__(*args, **kwargs) 

     def validate(self, data): 
      model_type = self.model_type 
      model_qs = ContentType.objects.filter(model=model_type) 
      if not model_qs.exists() or model_qs.count() != 1: 
       raise ValidationError("This is not a valid content type") 
      SomeModel = model_qs.first().model_class() 
      obj_qs = SomeModel.objects.filter(slug=self.slug) 
      if not obj_qs.exists() or obj_qs.count() != 1: 
       raise ValidationError("This is not a slug for this content type") 
      return data 

     def create(self, validated_data): 
      content = validated_data.get("content") 
      if user: 
       main_user = user 
      else: 
       main_user = User.objects.all().first() 
      model_type = self.model_type 
      slug = self.slug 
      parent_obj = self.parent_obj 
      comment = Comment.objects.create_by_model_type(
       model_type, slug, content, main_user, 
       parent_obj=parent_obj 
      ) 
      return comment 

    return CommentCreateSerializer 

這是視圖代碼:

class CommentCreateAPIView(CreateAPIView): 
    queryset = Comment.objects.all() 
    #serializer_class = PostCreateUpdateSerializer 
    permission_classes = [IsAuthenticated] 

    def get_serializer_class(self): 
     model_type = self.request.GET.get("type") 
     slug = self.request.GET.get("slug") 
     parent_id = self.request.GET.get("parent_id", None) 
     return create_comment_serializer(
       model_type=model_type, 
       slug=slug, 
       parent_id=parent_id, 
       user=self.request.user 
       ) 
+2

什麼'ContentType.objects.filter(model = model_type)'產生?因爲如果您使用原始['create_by_model_type()'](https://github.com/codingforentrepreneurs/Blog-API-with-Django-Rest-Framework/blob/ebce1ea22d6a70325c0f18ede52f44dc9a4671d5/src/comments/models.py#L36)當找不到類型時它返回'None'。 – dhke

+0

謝謝!沒有看到那裏的錯誤,只專注於api。 –

回答

0

不知何故您Comment.objects.create_by_model_type()不產生任何對象,並創建()方法沒」沒有發現任何事情要回來。

相關問題