6

我正在討論Django中的應用程序,它有線程,文章,回覆和投票。投票使用Generic Foreign Keys and Content Types來確保用戶只能對特定主題/帖子/回覆投票一次。GenericForeignKey,ContentType和DjangoRestFramework

投票模式是這樣的:

VOTE_TYPE = (
    (-1, 'DISLIKE'), 
    (1, 'LIKE'), 
) 

class Vote(models.Model): 
    user = models.ForeignKey(User) 
    content_type = models.ForeignKey(ContentType, 
     limit_choices_to={"model__in": ("Thread", "Reply", "Post")}, 
     related_name="votes") 
    object_id = models.PositiveIntegerField() 
    content_object = generic.GenericForeignKey('content_type', 'object_id') 
    vote = models.IntegerField(choices=VOTE_TYPE) 

    objects = GetOrNoneManager() 

    class Meta(): 
     unique_together = [('object_id', 'content_type', 'user')] 

投票串行:

class VoteSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Vote 

處理投票的觀點:

@api_view(['POST']) 
def discussions_vote(request): 

if not request.user.is_authenticated(): 
    return Response(status=status.HTTP_404_NOT_FOUND) 

data = request.DATA 

if data['obj_type'] == 'thread': 
    content_type = ContentType.objects.get_for_model(Thread) 

    print content_type.id 

    info = { 
     'content_type': content_type.id, 
     'user': request.user.id, 
     'object_id': data['obj']['id'] 
    } 

    vote = Vote.objects.get_or_none(**info) 

    info['vote'] = data['vote'] 

    ser = VoteSerializer(vote, data=info) 

    if ser.is_valid(): 
     print "Valid" 
    else: 
     pprint.pprint(ser.errors) 

return Response() 

request.DATA內容:

{u'vote': -1, 
u'obj_type': u'thread', 
u'obj': 
    { 
    ... 
    u'id': 7, 
    ... 
    } 
} 

當我投票,Django的REST框架串拋出一個錯誤:

Model content type with pk 149 does not exist. 

149是根據contentType的線程模型正確的ID,根據

print content_type.id 

我幾乎在造成這種情況的損失......

回答

4

該問題可能是因爲您有一個通用外鍵,可能會鏈接到任何類型的模型實例,所以沒有默認的REST框架確定方式如何表示序列化的數據。

看看該文檔上GFKs在這裏序列化器,希望這將有助於讓你開始... http://www.django-rest-framework.org/api-guide/relations#generic-relationships

如果你仍然發現它有問題,然後簡單地退出完全採用串行的,只是在視圖中顯式執行驗證,並返回您想要用於表示的任何值的字典。