Django Generic Relations Error: "Cannot resolve the keyword" content_object "to"

I use Django Generic Relations to define a voting model for question and answer models.

Here is my voting 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โ€ in the Django console, it prints the โ€œQuestion 1โ€ object. Therefore, I do not understand why the string "content_object = object" gives me a field error ...

Any ideas: (((???

thanks

+6
source share
1 answer

content_object is a kind of read-only attribute that retrieves the object specified in the content_type and object_id fields. You should replace your code with 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: The Django documentation directly states:

Due to the way GenericForeignKey is implemented, you cannot use such fields directly with filters (for example, filter () and exclude ()) through the database API. Since GenericForeignKey is not a regular 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) 
+14
source

Source: https://habr.com/ru/post/951748/


All Articles