I have below model and I want to perform below query:
Post.objects.select_related(
'previous_post', 'next_post'
).get(id=some_id)
# models.py
class Post(models.Model):
title = models.CharField(max_length=60, unique=True)
description = models.TextField()
content = models.TextField()
previous_post = models.OneToOneField('self', null=True, blank=True,
related_name='next_post',
on_delete=models.PROTECT)
For some reason it does not work with next_post parameter, as I get following error:
raise IndexError("Number of args exceeds number of fields")
IndexError: Number of args exceeds number of fields
Theoretically I can live without select_related, but I would prefer not to give up it in this case and I am really curious whether I am doing something wrong or this is just a Django bug.
Full traceback:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 381, in get
num = len(clone)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 240, in __len__
self._fetch_all()
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 72, in __iter__
rel_populator.populate(row, obj)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 1715, in populate
obj = self.model_cls.from_db(self.db, self.init_list, obj_data)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/base.py", line 460, in from_db
new = cls(*values)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/base.py", line 372, in __init__
raise IndexError("Number of args exceeds number of fields")
IndexError: Number of args exceeds number of fields
It looks like a bug in Django. I can reproduce in 1.8 and 1.9, but not in the master branch.
Doing a git bisect, tt appears to have been fixed by ticket 26207, so it should be fixed in Django 1.10.
Related
I encountered a strange behavior while applying a signal to a new model, I'm not sure to understand what is wrong but it seems related with the fact that I used abstract classes.
The models (simplified)
Basically, I have Article, Photo (inheriting from Post)
class Post(models.Model):
class Meta:
abstract = True
some_field = models.Something()
class Article(Post):
category = models.ForeignKey(Article_category, null=True, on_delete=models.SET_NULL)
some_field = models.Something()
class Photo(Post):
category = models.ForeignKey(Photo_category, null=True, on_delete=models.SET_NULL)
some_field = models.Something()
and their respective Categories
class Category(models.Model):
class Meta:
abstract = True
parent = models.ForeignKey('self', null=True, blank=True, related_name='nested_category', on_delete=models.SET_NULL)
name = models.CharField(max_length=50)
count = models.PositiveSmallIntegerField(default=0, editable=False)
class Article_category(Category):
#classmethod
def load(cls):
cache.set('{}'.format(cls.__name__), cls.objects.all())
class Photo_category(Category):
#classmethod
def load(cls):
cache.set('{}'.format(cls.__name__), cls.objects.all())
The signal
A straighforward incremental counter. Every time an article/photo is created, it's corresponding category count is updated and the entire model is saved in the cache (for templating purposes)
from django.db.models import F
#receiver(post_save, sender=Article) ----> here comes trouble
#receiver(post_save, sender=Photo)
def add_one_to_count(sender, instance, **kwargs):
cat = type(instance.category).objects.get(name=instance.category)
cat.count = F('count')+1
cat.save()
cache.set('{}_category'.format(sender.__name__), type(instance.category).objects.all())
The problem
What you saw above works like a charm for #receiver(post_save, sender=Photo) but when I add #receiver(post_save, sender=Article), DB initialization with fixture fails and I only get emptyset tables (mariaDB). This very line is the only one changing fail to success and I can't figure why. Since count is defined in the abstract class, I wondered whether it had something to do with it, for I did not have any issue applying a similar logic to categories:
# this works perfectly
#receiver(post_save, sender=Photo_category)
#receiver(post_delete, sender=Photo_category)
#receiver(post_save, sender=Article_category)
#receiver(post_delete, sender=Article_category)
def refresh_cached_category(sender, instance, using, **kwargs):
cache.set('{}'.format(type(instance).__name__), type(instance).objects.all())
Thanks for any enlightenment
The complete Traceback
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle
self.loaddata(fixture_labels)
File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 114, in loaddata
self.load_label(fixture_label)
File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 181, in load_label
obj.save(using=self.using)
File "/usr/local/lib/python3.7/site-packages/django/core/serializers/base.py", line 223, in save
models.Model.save_base(self.object, using=using, raw=True, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 790, in save_base
update_fields=update_fields, raw=raw, using=using,
File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send
for receiver in self._live_receivers(sender)
File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp>
for receiver in self._live_receivers(sender)
File "/usr/src/cms/website/observers.py", line 26, in add_one_to_count
cat = type(instance.category).objects.get(name=instance.category)
File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get
self.model._meta.object_name
website.models.DoesNotExist: Problem installing fixture '/usr/src/cms/../test/data_dev.yaml': Article_category matching query does not exist.
You can't filter on name=instance.category in your query, because that's not a str. You need to filter on name=instance.category.name but first you also need to make sure instance.category isn't None (since it can be).
The thing I don't understand is why you perform a query in the first place, just to fetch the same object: instance.category is the same as ArticleCategory.objects.get(name=instance.category.name) assuming the name is unique, except you do an extra query to the db.
Also the query will raise an exception if you have two categories with the same name (which you don't exclude in your model). So your code should be:
def add_one_to_count(sender, instance, **kwargs):
if instance.category:
instance.category.count = F('count')+1
instance.category.save()
cache.set('{}_category'.format(sender.__name__), type(instance.category).objects.all())
I have 2 models Car and Offer. The car table is an existing table filled with vehicle specifications. In the django admin I want to map an offer to an existing car in the specs table. This means that when a click on an offer in admin, I want to be able to see a list with all cars - find the correct one - and save it on the offer. Ive done this by populating the foreignkey field with a list of choices based on the the existing car objects.
models.py:
class Car(models.Model):
brand = models.TextField(max_length=300, default= "")
model = models.TextField(max_length=300, default= "")
edition = models.TextField(max_length=300, default= "")
engineVolume = models.FloatField(default=0.0)
def __unicode__(self):
return smart_unicode(self.brand)
carIds = []
idx = 1
for car in Car.objects.all():
carIds.append((idx, car))
idx = idx + 1
class Offer(models.Model):
stringUrl = models.TextField(max_length=300)
extractionDate = models.DateTimeField(default=datetime.datetime.now, blank=True)
cars = models.ForeignKey(Car, default= "", choices=carIds, null=True, to_field='id')
this works perfectly. I click on an offer in admin and I see a selectionbox populated with all existing cars. I find the correct car, save it, and the offers´s foreignkey car id in the database points to the correct vehicle.
But suddenly when I want to make later migrations django says it cannot serialze the car object?
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 143, in handle
self.write_migration_files(changes)
File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 171, in write_migration_files
migration_string = writer.as_string()
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 166, in as_string
operation_string, operation_imports = OperationWriter(operation).serialize()
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 124, in serialize
_write(arg_name, arg_value)
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 87, in _write
arg_string, arg_imports = MigrationWriter.serialize(_arg_value)
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 377, in serialize
return cls.serialize_deconstructed(path, args, kwargs)
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 268, in serialize_deconstructed
arg_string, arg_imports = cls.serialize(arg)
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 303, in serialize
item_string, item_imports = cls.serialize(item)
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 303, in serialize
item_string, item_imports = cls.serialize(item)
File "/usr/local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 465, in serialize
"topics/migrations/#migration-serializing" % (value, get_docs_version())
`enter code here`ValueError: Cannot serialize: <Car: Nissan>
There are some values Django cannot serialize into migration files.
For more, see https://docs.djangoproject.com/en/1.8/topics/migrations/#migration- serializing
I have no idea why this error occurs. I' m new to django and the just starting with the admin. I´ve been reading up on serialzation and deconstruction but cant see how to apply it here? Perhaps I should follow a different route to achieve what I want?
In my case I was tring to add a field like:
task = models.ForeignKey(Task, on_delete=models.CASCADE, default=Task.objects.first())
but corrected this by using:
task = models.ForeignKey(Task, on_delete=models.CASCADE, default=Task.objects.first().pk)
In a nutshell you don't need choices at all.
choices, although can be any iterable and can be modified, is more suited for static data.
Afterwards, this piece of code
carIds = []
idx = 1
for car in Car.objects.all():
carIds.append((idx, car))
idx = idx + 1
achieves nothing.
First, you are not filtering the choices in any way, just converting them to a list of tuples. Second, having a ForeignKey automatically provides choices from the referenced model's unfiltered queryset e.g. Car.objects.all().
So you could just drop choices, and if you need filtering in ModelForm and admin use ForeignKey.limit_choices_to instead.
I'm trying to use generic foreign keys, but I can't seem to get them to work properly.
First, some context: I've got a messaging app and a groups app. Now, I want to be able to have players/groups write pms (private messages) to other users/groups. Here's my Pm model:
class Pm(models.Model):
"""Represents a private message (a la email) from one user to another."""
title = models.CharField(max_length=settings.max_title_length, default="(Blank)")
slug = models.SlugField(max_length=settings.max_title_length, editable=False)
#This was my code from when I only allowed pms to go from user to another
#user
#author = models.ForeignKey(Player, related_name="written_messages")
#recipient = models.ForeignKey(Player, related_name="recieved_messages")
text = models.TextField(max_length=settings.max_post_length)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
#Both will be either a group or a player
author = generic.GenericForeignKey('content_type', 'object_id')
recipient = generic.GenericForeignKey('content_type', 'object_id')
#[snip]
and here's the relevant bits of my Group and Player models:
class Group(models.Model):
#[snip]
written_messages = generic.GenericRelation("messaging.Pm")
sent_messages = generic.GenericRelation("messaging.Pm")
class Player(My_Model):
user = models.OneToOneField(User)
#[snip]
written_messages = generic.GenericRelation("messaging.Pm")
sent_messages = generic.GenericRelation("messaging.Pm")
Does this look correct?
When I run it, I get this traceback (so obviously something's wrong):
Traceback (most recent call last):
File "/usr/local/lib/python3.2/dist-packages/django/core/urlresolvers.py", line 339, in urlconf_module
return self._urlconf_module
AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.2/wsgiref/handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python3.2/dist-packages/django/contrib/staticfiles/handlers.py", line 72, in __call__
return self.application(environ, start_response)
File "/usr/local/lib/python3.2/dist-packages/django/core/handlers/wsgi.py", line 180, in __call__
self.load_middleware()
File "/usr/local/lib/python3.2/dist-packages/django/core/handlers/base.py", line 49, in load_middleware
mw_instance = mw_class()
File "/usr/local/lib/python3.2/dist-packages/django/middleware/locale.py", line 24, in __init__
for url_pattern in get_resolver(None).url_patterns:
File "/usr/local/lib/python3.2/dist-packages/django/core/urlresolvers.py", line 346, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python3.2/dist-packages/django/core/urlresolvers.py", line 341, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/lib/python3.2/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/mark/Dropbox/Public/Galcon/galcon/galcon/urls.py", line 40, in <module>
("^messages/", include("messaging.urls")),
File "/usr/local/lib/python3.2/dist-packages/django/conf/urls/__init__.py", line 26, in include
urlconf_module = import_module(urlconf_module)
File "/usr/local/lib/python3.2/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/mark/Dropbox/Public/Galcon/galcon/messaging/urls.py", line 3, in <module>
from . import views
File "/home/mark/Dropbox/Public/Galcon/galcon/messaging/views.py", line 10, in <module>
from . import my_forms
File "/home/mark/Dropbox/Public/Galcon/galcon/messaging/my_forms.py", line 5, in <module>
class Modify_Message_Form(forms.ModelForm):
File "/usr/local/lib/python3.2/dist-packages/django/forms/models.py", line 283, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (recipient) specified for Pm
The mentioned form is pretty simple:
class Modify_Message_Form(forms.ModelForm):
class Meta:
model = Pm
fields = ["title", "recipient", "text"]
What have I done wrong? Thanks!
Using the name of the GenericForeignKey in the form doesn't work as it's not actually a real field but more of a convenience. There's no widget to display the relationship; you usually display the content_type and object_id. If you want to see the relationship in the admin interface then I'd recommend looking at Grappelli.
You also need content_type and object_id fields for each GenericForeignKey.
author_content_type = models.ForeignKey(ContentType)
author_object_id = models.PositiveIntegerField()
recipient_content_type = models.ForeignKey(ContentType)
recipient_object_id = models.PositiveIntegerField()
author = generic.GenericForeignKey('author_content_type', 'author_object_id')
recipient = generic.GenericForeignKey('recipient_content_type', 'recipient_object_id')
I've not much experience with GenericRelations but from what I know you'd also need to specify the content_type and object_id fields in your Player and Group models.
written_messages = generic.GenericRelation(messaging.Pm
content_type_field='author_content_type',
object_id_field='author_object_id')
It seems, by looking at the traceback, that you cannot use GenericForeignKeys as form fields. But I think you can use recipient_content_type and recipient_content_id instead, which is what Django admin usually shows to users.
Please I need help with this code:
>>> t = Transaction.objects.filter(paid=True)
>>> t
[<Transaction: ac0e95f6cd994cc39807d986f7a10d4d>, <Transaction: 7067361871fd459f
aa144988ffa22c7c>, <Transaction: 134e5ab4b0a74b5a985ff53e31370818>, <Transaction
: ef451670efad4995bff755621c162807>]
>>> t[0]
<Transaction: ac0e95f6cd994cc39807d986f7a10d4d>
>>> t[0].branch_name
<Branch: WAREHOUSE ROAD>
>>> Transaction.objects.get(branch_name='WAREHOUSE ROAD')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\mana
ger.py", line 132, in get
return self.get_query_set().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 344, in get
num = len(clone)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 82, in __len__
self._result_cache = list(self.iterator())
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 273, in iterator
for row in compiler.results_iter():
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\sql\
compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\sql\
compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\backends\ut
il.py", line 34, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\backends\my
sql\base.py", line 86, in execute
return self.cursor.execute(query, args)
File "build\bdist.win32\egg\MySQLdb\cursors.py", line 176, in execute
if not self._defer_warnings: self._warning_check()
File "build\bdist.win32\egg\MySQLdb\cursors.py", line 92, in _warning_check
warn(w[-1], self.Warning, 3)
Warning: Truncated incorrect DOUBLE value: 'WAREHOUSE ROAD'
Here is Branch and Transaction models:
class Branch(models.Model):
""" Branch """
bid = models.AutoField(primary_key=True)
institution = models.CharField(max_length=50)
branchcode = models.CharField(max_length=50)
name_branch = models.CharField(max_length=255)
name_branch_short = models.CharField(max_length=50)
address_1 = models.CharField(max_length=100)
name_city = models.CharField(max_length=50)
name_state = models.CharField(max_length=50)
sector = models.CharField(max_length=50)
class Meta:
db_table = u'branch'
def __unicode__(self):
return self.name_branch
class Transaction(models.Model):
"""Gateway transactions"""
id = models.AutoField(primary_key=True)
tpin = UUIDField(max_length=32, blank=True, editable=False,\
help_text='Transaction Payment Identification Number')
user_id = models.IntegerField(help_text='The user who made the transaction')
amount = models.DecimalField(max_digits=14, decimal_places=2, \
help_text='Transaction amount')
identifier = models.CharField(max_length=100, blank=True, \
help_text='A unique identifier provided by the student')
institution = models.ForeignKey(Institution, related_name='transactions')
financial_institution = models.ForeignKey('FinancialInstitution', blank=True, null=True, related_name='transactions', help_text='The financial institution this transaction was updated in')
branch_name = models.ForeignKey(Branch, blank=True, null=True, related_name='transactions', \
help_text='The bank branch where this transaction is originating from')
paid = models.BooleanField(default=False)
teller_no = models.CharField(max_length=20, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
audit_log = AuditLog(exclude=['created', 'updated', ])
def __unicode__(self):
return self.tpin
def natural_key(self):
""" A natural key is a tuple of values that can be used to uniquely identify an object
instance without using the primary key value.
"""
return self.tpin
I tried to serialize Transaction like this:
>>> from django.core import serializers
>>> serializers.serialize('csv', t)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\__init__.py", line 91, in serialize
s.serialize(queryset, **options)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\base.py", line 48, in serialize
self.handle_fk_field(obj, field)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\python.py", line 48, in handle_fk_field
related = getattr(obj, field.name)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\fiel
ds\related.py", line 315, in __get__
rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 349, in get
% self.model._meta.object_name)
DoesNotExist: Branch matching query does not exist.
I don't understanding why get is returning DoesNotExists on Branch. I showed an example above which shows that Branch has a record in Transaction.
Looping through t I get a result, but then followed by DoesNotExist: Branch matching query does not exist
>>> for i in t:
... i.branch_name
...
<Branch: WAREHOUSE ROAD>
Traceback (most recent call last):
File "<console>", line 2, in <module>
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\fiel
ds\related.py", line 315, in __get__
rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 349, in get
% self.model._meta.object_name)
DoesNotExist: Branch matching query does not exist.
Please help. Thanks
This query:
Transaction.objects.get(branch_name='WAREHOUSE ROAD')
filters for branch_name which is a ForeignKey field. To query on that name, you should use two underscores:
Transaction.objects.get(branch_name__name_branch='WAREHOUSE ROAD')
Not the most convenient names for your fields...
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")