python - Django 通用关系错误 : "cannot resolve keyword ' content_object' into field"

标签 python django django-class-based-views

我正在使用 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')



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

任何想法:(((???

谢谢

最佳答案

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明确说明:

Due to the way GenericForeignKey is implemented, you cannot use such fields directly with filters (filter() and exclude(), for example) via the database API. Because a GenericForeignKey isn’t a normal field object, these examples will not work:

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

关于python - Django 通用关系错误 : "cannot resolve keyword ' content_object' into field",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18239030/

相关文章:

python - 修改 pandas 数据框中的行子集

python - 安装 Numexpr 的问题(结果是 PyTables)

python - Django 南错误 : "there is no enabled application matching ' myapp'"

django - 如何使用 CreateView 将用户对象传递到 Modelform

django - UpdateView 中的多个模型

python - 将文件转换为字典

python - save() 上的 Django Rest Framework 完整性错误,is_valid() 返回 true

python - 导入错误 : No module named 'Crypto' on Mac (Pycrypto is up-to-date)

html - 在 Django 中使用 rowspan 进行分组并重新分组

python - 在基于类的 View 中返回 template_name + args