Opened 5 years ago

Closed 5 years ago

#31130 closed Bug (invalid)

GenericRelation error if not use default field name for GenericForeignKey

Reported by: inkawarrior Owned by: nobody
Component: Core (Cache system) Version: 3.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If change the name of either content_type or object_id field from the example https://docs.djangoproject.com/en/3.0/ref/contrib/contenttypes/#generic-relations

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    bookmark_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'bookmark_id')

    def __str__(self):
        return self.tag

class Bookmark(models.Model):
    url = models.URLField()
    tags = GenericRelation(TaggedItem)

And run the code from the example

>>> b = Bookmark(url='https://www.djangoproject.com/')
>>> b.save()
>>> t1 = TaggedItem(content_object=b, tag='django')
>>> t1.save()
>>> t2 = TaggedItem(content_object=b, tag='python')
>>> t2.save()
>>> b.tags.all()

Will get the following error

  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\contenttypes\fields.py", line 560, in get_queryset
    return self.instance._prefetched_objects_cache[self.prefetch_cache_name]
AttributeError: 'Bookmark' object has no attribute '_prefetched_objects_cache'

django.core.exceptions.FieldError: Cannot resolve keyword 'object_id' into field. Choices are: bookmark_id, content_object, content_type, content_type_id, id, tag

The is no problem when using the default name

Change History (1)

comment:1 by Simon Charette, 5 years ago

Resolution: invalid
Status: newclosed

You have to pass object_id_field='bookmark_id' to tags = GenericRelation(TaggedItem) as documented

... if the model which has the generic foreign key is using non-default names for those fields, you must pass the names of the fields when setting up a GenericRelation to it.

Please use support channels before submitting a bug report.

Note: See TracTickets for help on using tickets.
Back to Top