Opened 8 years ago

Closed 8 years ago

#27740 closed New feature (wontfix)

Allow content_type or object_id of GenericForeignKey to be field on related model

Reported by: Chris Morbitzer Owned by: nobody
Component: contrib.contenttypes Version: 1.10
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

I would like to specify a related model field as the values of content_type or object_id of GenericForeignKey. For example:

class Widget(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)

class Gadget(models.Model):
    widget = models.ForeignKey(Widget, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('widget__content_type', 'object_id')

If I tried to use this now, I would get the error:

Traceback (most recent call last):
  File "django/db/models/options.py", line 617, in get_field
    return self.fields_map[field_name]
KeyError: 'widget__content_type'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "django/contrib/contenttypes/fields.py", line 224, in __get__
    f = self.model._meta.get_field(self.ct_field)
  File "django/db/models/options.py", line 619, in get_field
    raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, field_name))
django.core.exceptions.FieldDoesNotExist: Gadget has no field named 'widget__content_type'

One use case for this is a generic custom attribute system, where attribute fields can be created for any other model. The "fields" model has the content_type field. The "values" model has the object ID and value fields. The developer would like to query the object that the "values" record references: value.content_object

Change History (1)

comment:1 by Tim Graham, 8 years ago

Resolution: wontfix
Status: newclosed

The usual advise is to avoid GenericForeignKey in the first place. I doubt there would be consensus to add that complexity, if it's even feasible. If you can offer patch, please raise the idea on the DevelopersMailingList to see what other think.

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