6

我正在使用 Django 的通用关系来定义问答模型的投票模型。

这是我的投票模型:

模型.py

class Vote(models.Model):
    user_voted = models.ForeignKey(MyUser)
    is_upvote = models.BooleanField(default=True)

    # Generic foreign key
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    class Meta:
        unique_together = ('content_type', 'user_voted')



视图.py

        user_voted = MyUser.objects.get(id=request.user.id)
        object_type = request.POST.get('object_type')

        object = None;
        if object_type == 'question':
            object = get_object_or_404(Question, id=self.kwargs['pk'])
        elif object_type == 'answer':
            object = get_object_or_404(Answer, id=self.kwargs['pk'])

        # THIS LAST LINE GIVES ME THE ERROR
        vote, created = Vote.objects.get_or_create(user_voted=user_voted, content_object=object)



然后我得到这个错误:

FieldError at /1/ 
Cannot resolve keyword 'content_object' into field. Choices are: answer, content_type, id, is_upvote, object_id, question, user_voted



当我将“对象”打印到 Django 控制台时,它会打印“问题 1”对象。所以我不明白为什么“content_object = object”行给了我字段错误......

有任何想法吗 :(((???

谢谢

4

1 回答 1

15

content_object是一种只读属性,它将检索由字段content_type和指定的对象object_id。您应该将代码替换为以下内容:

from django.contrib.contenttypes.models import ContentType
type = ContentType.objects.get_for_model(object)
vote, created = Vote.objects.get_or_create(user_voted=user_voted, content_type=type, object_id=object.id)

编辑: Django文档明确指出:

由于 GenericForeignKey 的实现方式,您不能通过数据库 API 直接将此类字段与过滤器(例如 filter() 和 exclude())一起使用。因为 GenericForeignKey 不是普通的字段对象,所以这些示例将不起作用:

# This will fail
>>> TaggedItem.objects.filter(content_object=guido)
# This will also fail
>>> TaggedItem.objects.get(content_object=guido)
于 2013-08-14T18:29:29.947 回答