Error while select_related query - django

I have Question and QuestionChoices models as below, when I try to retrieve the Question and related Answers from the Questionchoices I get the below error saying that the query is expecting string. What could be wrong model/query?
class Question(models.Model):
Question_Id = models.AutoField(primary_key=True)
Question_Text = models.TextField(max_length=1000)
def __str__(self):
return self.Question_Text
def __int__(self):
return self.Question_Id
class QuestionChoices(models.Model):
Choice_Id = models.AutoField(primary_key=True)
Question_Choices_Question_Id = models.ForeignKey("Question", on_delete=models.CASCADE)
Choice = models.TextField(max_length=500)
Is_Right_Choice = models.BooleanField(default=False)
>>> QuestionChoices.objects.select_related().filter(Question_Choices_Question_Id = Question.Question_Id)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 836, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 854, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1253, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1277, in _add_q
split_subq=split_subq,
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1215, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\query.py", line 1085, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\lookups.py", line 18, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "C:\Users\adm\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\__init__.py", line 947, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'

I got the same error after running your shell command. The problem is caused by the way the code's filter() is set-up. The argument requires a model object OR foreign key as the value.
Answer:
python3 manage.py shell
>>> from my_app.models import *
>>> my_question_obj = Question.objects.create(Question_Text = "This is my question")
>>> QuestionChoices.objects.select_related().filter(Question_Choices_Question_Id=my_model_obj)
Alternatively if you already have a question you would like to filter on in your database you can use get() to retrieve the object.
python3 manage.py shell
>>> from my_app.models import *
>>> my_question_obj = Question.objects.get(Question_Text="This is the text of your question")
>>> QuestionChoices.objects.select_related().filter(Question_Choices_Question_Id = my_model_obj)

Related

how do i solve the following Django serializer error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Article'

Im quite new to django but i cant find the solution in the docs
My question:
I have a model with 2 OneToOne relations:
class Slotting(ICSBaseMixin):
# database fields
article = models.OneToOneField(
"ics_stock.Article",
on_delete=models.CASCADE,
related_name="slotting",
null=False
)
article_location = models.OneToOneField(
"ics_stock.ArticleLocation",
on_delete=models.CASCADE,
null=False,
related_name="slotting"
)
def __str__(self):
return str(self.record_id)
class Meta:
db_table = "ICS_Stock_Slotting"
verbose_name = "Slotting"
verbose_name_plural = "Slottings" # noqa
I want to create and save a new instance through a serializer.
serializer:
class SlottingCreateUpdateSerializer(serializers.ModelSerializer):
def update(self, instance, validated_data):
article = validated_data.pop("article")
instance.article_id = article
article_location = validated_data.pop("article_location")
instance.article_location_id = article_location
instance.save()
return instance
def create(self, validated_data):
article_id = validated_data.pop("article")
article = get_object_or_404(
Article,
record_id=article_id
)
article_location_id = validated_data.pop("article_location")
article_location = get_object_or_404(
ArticleLocation,
record_id=article_location_id
)
slotting = Slotting()
slotting.article_location = article_location,
slotting.article = article
slotting.save()
return slotting
Now when trying to serialize and save i get the following error:
raceback (most recent call last):
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Article'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\views\generic\base.py", line 84, in view
return self.dispatch(request, *args, **kwargs)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\000 Projects\Applications\ICS_Django_core\ics_stock\api\views\slotting.py", line 44, in post
instance = validated_data.save()
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "C:\000 Projects\Applications\ICS_Django_core\ics_stock\api\serializers\slotting.py", line 40, in create
article = get_object_or_404(
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\shortcuts.py", line 85, in get_object_or_404
return queryset.get(*args, **kwargs)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\query.py", line 482, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\query.py", line 1071, in filter
return self._filter_or_exclude(False, args, kwargs)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\sql\query.py", line 1448, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\sql\query.py", line 1273, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\lookups.py", line 27, in __init__
self.rhs = self.get_prep_lookup()
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\lookups.py", line 85, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
TypeError: Field 'record_id' expected a number but got <Article: test article>.
Now im googling and looking for a whole day but i still dont know what im doing wrong.
What do i need to refactor to be able to fix the bug.
I created a serializer class to inherrit from that uses a dict input from the Meta class.
class RelatedModelSerializer(serializers.ModelSerializer):
"""
serializes all relationship based models
added field for Meta class
- relationships: dict[str:Model]
Create and update method adds all fields from relationships with the primary key with from model described in relationships dict and saves and raises HTTP404 when object not found
- Arjen Keller
"""
class Meta:
relationships = {}
model = None
def create(self, validated_data):
for key in frozenset(validated_data):
if self.Meta.relationships and key in self.Meta.relationships:
validated_data[f"{key}_id"] = get_object_or_404(
self.Meta.relationships[key],
record_id=validated_data.pop(key).id
).id
return self.Meta.model.objects.create(**validated_data)
def update(self, instance, validated_data):
for key in frozenset(validated_data):
setattr(
instance, f"{key}_id",
validated_data.pop(key)
) if self.Meta.relationships and key in self.Meta.relationships and get_object_or_404(
self.Meta.relationships[key],
record_id=validated_data[key].id
).id else setattr(
instance,
f"{key}",
validated_data.pop(key)
)
instance.save(**validated_data)
return instance
i hope it helps somebody.

"django.core.exceptions.ValidationError: ['“post_id” is not a valid UUID.']" with seemingly valid UUID

This is a simple blog app I am creating. I have a model that creates an article and generates a UUID for each article created. This functions as expected.
I am now attempting to create a view variable that contains the "post_id" object from my model "Post" so that I can later insert this variable into my html template. The confusing thing is I know the Post model generates a valid UUID (at least my understand of UUIDs) as I have seen it generated so I am unclear where to start looking to resolve this issue. Other similar issues online do not seem to be related to my issue.
myapp/views.py
from django.shortcuts import render
from django.utils import timezone
from .models import Post
def blog_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
post_uid = Post.objects.get(pk="post_id")
context = {
"post_uid": post_uid,
"posts": posts
}
return render(request, 'blog/blog_list.html', context)
def article(request, post_id):
current_article = Post.objects.get(pk=post_id)
return render(request, 'blog/article.html', {'current_article':current_article})
myapp/model.py
from django.db import models
from django.conf import settings
from django.utils import timezone
import uuid
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Errors Returned
Internal Server Error: /blog/
Traceback (most recent call last):
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2434, in to_python
return uuid.UUID(**{input_form: value})
File "/usr/lib/python3.8/uuid.py", line 171, in __init__
raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/taylor/tc_site/blog/views.py", line 7, in blog_list
post_uid = Post.objects.get(pk="post_id")
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 424, in get
clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 941, in filter
return self._filter_or_exclude(False, args, kwargs)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 968, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1393, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q
child_clause, needed_inner = self.build_filter(
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1347, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1193, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/lookups.py", line 25, in __init__
self.rhs = self.get_prep_lookup()
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/lookups.py", line 77, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2418, in get_prep_value
return self.to_python(value)
File "/home/taylor/tc_site/virtualenv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2436, in to_python
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“post_id” is not a valid UUID.']
Also, in case it is valuable- the latest migration file from when the post_id object was added.
myapp/migrations/0002_auto_20210830_1450.py
from django.db import migrations, models
import uuid
def create_uuid(apps, schema_editor):
Post = apps.get_model('blog', 'Post')
for x in Post.objects.all():
x.post_id = uuid.uuid4()
x.save()
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='id',
),
migrations.AddField(
model_name='post',
name='post_id',
field=models.UUIDField(blank=True, null=True),
),
migrations.RunPython(create_uuid),
migrations.AlterField(
model_name='post',
name='post_id',
field=models.UUIDField(default=uuid.uuid4, unique=True)
)
]
Your query looks wrong. You used quotes around post_id
post_uid = Post.objects.get(pk="post_id")
try this instead of above without quotes:
post_uid = Post.objects.get(pk=post_id)
Also there is no post_id parameter in your blog_list method. You need to pass post_id parameter to this method.

Can't save new objects in Django full-text search with PostgreSQL

I'm following this post on how to add full-text functionality to my Django app. I have the following model:
class CustomUser(AbstractUser):
email = models.EmailField(_('email address'), unique=True)
class Author(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete = models.CASCADE)
name = models.CharField(max_length = 250)
alternative_names = ArrayField(models.CharField(max_length = 250),blank=True,null=True)
name_norm = models.CharField(max_length = 250,blank=True,null = True)
slug = models.CharField(max_length = 250,unique = True)
photo = models.ImageField(upload_to = 'imgs/users/%Y/%m/%d',blank = True)
search_vector = SearchVectorField(null=True)
def save(self, *args, **kwargs):
self.search_vector = (SearchVector('name', weight='A') )
super().save(*args, **kwargs)`enter code here`
And when I try to save a new author with save:
autor = Author(user = utilizador,name = author_name,alternative_names = alternative_names,name_norm = name_norm,slug = slug)
autor.save()
I get the error:
Traceback (most recent call last):
File "populate_v2.py", line 140, in <module>
autor.save()
File "/home/mwon/NewArquivoOpiniao/webapp/colunadeopiniao/accounts/models.py", line 57, in save
super().save(*args, **kwargs)
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 748, in save
self.save_base(using=using, force_insert=force_insert,
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 785, in save_base
updated = self._save_table(
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 890, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/base.py", line 927, in _do_insert
return manager._insert(
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1393, in execute_sql
for sql, params in self.as_sql():
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1336, in as_sql
value_rows = [
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1337, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1337, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/home/mwon/NewArquivoOpiniao/env3.8/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1263, in prepare_value
raise ValueError(
ValueError: Failed to insert expression "SearchVector(Col(accounts_author, accounts.Author.name), weight=A)" on accounts.Author.search_vector. F() expressions can only be used to update, not to insert.
Django version: 3.0.11
F() expressions can only be used to update, not to insert.
I'm no expert on VectorField, but maybe the weight='A' is causing the F() expression. Does it work without weight, as shown in the tutorial you refer to?
Otherwise, try an update:
Author.objects.all().update(search_vector=SearchVector('name', weight='A'))
The error message is saying that you are trying to insert a value into the search_vector field when creating a new object of Author, but the SearchVector class only supports updating existing objects, not creating new ones. To solve this, you can change the implementation of the save method to update the search_vector field after the object has been created:
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
Author.objects.filter(pk=self.pk).update(search_vector=SearchVector('name', weight='A'))
This way, you can create the object first, and then update the vector.

Cannot add ManyToManyField objects in Django

I am unable to add ManyToManyField objects even after following the doc
models.py
class Label(models.Model):
...
name = models.CharField(blank=False, max_length=100)
class Template(models.Model):
...
labels = models.ManyToManyField(Label, blank=True, related_name="labels")
And then
>>> from content.models import Label, Template
>>> l1 = Label.objects.get_or_create(name='one') # saves in db
>>> l2 = Label.objects.get_or_create(name='two') # saves in db
>>> t1 = Template.objects.get(pk=1) # loads existing
>>> t1.labels.set([l1,l2]) # fails
throws this error
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1007, in set
self.add(*new_objs)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1083, in _add_items
'%s__in' % target_field_name: new_ids,
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/query.py", line 784, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1250, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1276, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1206, in build_filter
condition = lookup_class(lhs, value)
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in get_prep_lookup
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in <listcomp>
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 966, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Label'
I am using Django 1.11 on Python 3.6.
You are using get_or_create which returns a tuple of (object, created), not just an object.
So l1 and l2 are not Label objects as you assume, but tuples. Passing this to the many-to-many manager will not work.
Change your code as follows:
from content.models import Label, Template
# Ignore the second item returned by get_or_create
l1, _ = Label.objects.get_or_create(name='one')
l2, _ = Label.objects.get_or_create(name='two') #
t1 = Template.objects.get(pk=1)
t1.labels.set([l1,l2])

Django generic relation field reports that all() is getting unexpected keyword argument when no args are passed

I have a model which can be attached to to other models.
class Attachable(models.Model):
content_type = models.ForeignKey(ContentType)
object_pk = models.TextField()
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
class Meta:
abstract = True
class Flag(Attachable):
user = models.ForeignKey(User)
flag = models.SlugField()
timestamp = models.DateTimeField()
I'm creating a generic relationship to this model in another model.
flags = generic.GenericRelation(Flag)
I try to get objects from this generic relation like so:
self.flags.all()
This results in the following exception:
>>> obj.flags.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 105, in all
return self.get_query_set()
File "/usr/local/lib/python2.6/dist-packages/django/contrib/contenttypes/generic.py", line 252, in get_query_set
return superclass.get_query_set(self).filter(**query)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 498, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 516, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1675, in add_q
can_reuse=used_aliases)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1569, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1737, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'object_id' into field. Choices are: content_type, flag, id, nestablecomment, object_pk, timestamp, user
>>> obj.flags.all(object_pk=obj.pk)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: all() got an unexpected keyword argument 'object_pk'
What have I done wrong?
You need to define object_id_field and content_type_field when creating GenericRelation:
flags = generic.GenericRelation(Flag, object_id_field="object_pk", content_type_field="content_type")