Django Generic Relations error: “cannot resolve ke

2020-07-10 10:26发布

问题:

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



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 :(((???

Thanks

回答1:

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)

Edit: Django documentation explicitly remarks:

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)