django - GenericForeignKey、ContentType 和 DjangoRestFramework

标签 django django-models django-rest-framework django-contenttypes generic-foreign-key

我正在 Django 中开发一个讨论应用程序,它包含主题、帖子、回复和投票。投票使用 Generic Foreign Keys and Content Types以确保用户只能对特定主题/帖子/回复投票一次。

投票模型如下所示:

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

处理投票的 View :
@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 Framework 序列化程序抛出一个错误:
Model content type with pk 149 does not exist.  

149 是 Thread 模型的 ContentType 的正确 id,根据
print content_type.id

我对可能导致这种情况的原因感到非常茫然......

最佳答案

问题可能是您在那里有一个通用外键,它可以链接到任何类型的模型实例,因此 REST 框架没有确定如何表示序列化数据的默认方式。

在此处查看有关序列化程序中 GFK 的文档,希望它可以帮助您入门... http://www.django-rest-framework.org/api-guide/relations#generic-relationships

如果您仍然发现它有问题,那么只需完全放弃使用序列化程序,只需在 View 中显式执行验证,并返回您想要用于表示的任何值的字典。

关于django - GenericForeignKey、ContentType 和 DjangoRestFramework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22069806/

相关文章:

python - Django "before dispatch"混合

django - Django order_by属性

python - django-rest-framework:在 ViewSet 更新方法中添加额外的权限

django - 将所有序列化器字段设置为必需

django - 如何为 Django Rest HTTP 请求设置超时

尝试使用 devserver 提供静态文件时,Django channel 出错

django - 如何在运行时回退到 Django 中的多种语言?

python - Django 迁移失败 - 无法查询 "peterson": Must be "User" instance

python - 在一对多 Django 模型和模型形式上使用获取或插入功能

django - 如何过滤这些Django记录?