【问题标题】:GenericForeignKey, ContentType and DjangoRestFrameworkGenericForeignKey、ContentType 和 DjangoRestFramework
【发布时间】:2014-03-30 23:00:18
【问题描述】:

我正在 Django 中开发一个讨论应用程序,其中包含线程、帖子、回复和投票。 Votes 使用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

处理投票的视图:

@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

我几乎不知道是什么原因造成的......

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多