Django Generic Relations错误:“无法将关键字'content_object'解析为字段”

时间:2013-08-14 18:04:50

标签: python django django-class-based-views

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

这是我的投票模型:

models.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')



views.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”给我字段错误...

任何想法:(((???

由于

1 个答案:

答案 0 :(得分:14)

content_object是一种只读属性,用于检索字段content_typeobject_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 documentation明确说明:

  

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

# This will fail
>>> TaggedItem.objects.filter(content_object=guido)
# This will also fail
>>> TaggedItem.objects.get(content_object=guido)