我正在 Django 中开发一个讨论应用程序,它有线程、帖子、回复和投票。投票使用通用外键和内容类型来确保用户只能对特定线程/帖子/回复投票一次。
投票模型如下所示:
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
我几乎不知道可能导致这种情况的原因......