【问题标题】:Django Generic Relations error: "cannot resolve keyword 'content_object' into field"Django通用关系错误:“无法将关键字'content_object'解析为字段”
【发布时间】:2013-08-14 18:04:50
【问题描述】:

我正在使用 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”这行给了我字段错误...

任何想法:(((???

谢谢

【问题讨论】:

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


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 2014-07-04
      • 1970-01-01
      • 2011-07-07
      • 2021-11-18
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      相关资源
      最近更新 更多