Django Generic Relations error: cannot resolve keyword content_object into field

2024/11/16 7:50:40

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 keycontent_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 ERRORvote, 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

Answer

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)
https://en.xdnf.cn/q/71696.html

Related Q&A

How to benchmark unit tests in Python without adding any code

I have a Python project with a bunch of tests that have already been implemented, and Id like to begin benchmarking them so I can compare performance of the code, servers, etc over time. Locating the …

Digit recognition with Tesseract OCR and python

I use Tesseract and python to read digits (from a energy meter). Everything works well except for the number "1". Tesseract can not read the "1" Digit.This is the picture I send t…

Pycharm not recognizing packages even when __init__.py exits

This is my directory structure--> ProjectDirectory-->__init__.py--> BaseDirectory-->__init__.py--> AnotherBaseDirectory-->__init__.py-->program.pyinside program.pyWhen i give impor…

Scrapy is following and scraping non-allowed links

I have a CrawlSpider set up to following certain links and scrape a news magazine where the links to each issue follow the following URL scheme:http://example.com/YYYY/DDDD/index.htm where YYYY is the …

Overriding virtual methods in PyGObject

Im trying to implement the Heigh-for-width Geometry Management in GTK with Python for my custom Widget. My widget is a subclass from Gtk.DrawingArea and draws some parts of an Image.As I understood the…

How to find if two numbers are consecutive numbers in gray code sequence

I am trying to come up with a solution to the problem that given two numbers, find if they are the consecutive numbers in the gray code sequence i.e., if they are gray code neighbors assuming that the …

How do I get data from selected points in an offline plotly python jupyter notebook?

Example code:from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport plotly.graph_objs as goimport numpy as npN = 30 random_x = np.random.randn(N) random_y = np.random.randn…

Set background colour for a custom QWidget

I am attempting to create a custom QWidget (from PyQt5) whose background colour can change. However, all the standard methods of setting the background colour do not seem to work for a custom QWidget c…

Plotly: How to set up a color palette for a figure created with multiple traces?

I using code below to generate chart with multiple traces. However the only way that i know to apply different colours for each trace is using a randon function that ger a numerico RGB for color. But r…

Which implementation of OrderedDict should be used in python2.6?

As some of you may know in python2.7/3.2 well get OrderedDict with PEP372 however one of the reason the PEP existed was because everyone did their own implementation and they were all sightly incompati…