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

如果你仍然发现它有问题,然后简单地退出完全采用串行的,只是在视图中显式执行验证,并返回您想要用于表示的任何值的字典。