Django通用关系错误:& quot;无法解析关键字' content_object'进入现场" [英] Django Generic Relations error: "cannot resolve keyword 'content_object' into field"

查看:40
本文介绍了Django通用关系错误:& quot;无法解析关键字' content_object'进入现场"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django的通用关系为Question和Answer模型定义Vote模型.

I'm using Django's Generic Relations to define Vote model for Question and Answer models.

这是我的投票模型:

Here is my vote model:

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)



然后我得到这个错误:



And then I get this error:

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



When I print the "object" to Django console, it prints "Question 1" object. So I don't understand why the line "content_object=object" gives me the field error...

任何想法:((((???

Any ideas :(((???

谢谢

推荐答案

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

content_object is a sort of read-only attribute that will retrieve the object specified by fields content_type and object_id. You should replace your code by the following:

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

Django documentation explicitly remarks:

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

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)

这篇关于Django通用关系错误:& quot;无法解析关键字' content_object'进入现场"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆