Opened 8 years ago

Last modified 3 months ago

#27580 new New feature

add special field for storing content types

Reported by: Sergey Fedoseev Owned by:
Component: contrib.contenttypes Version: dev
Severity: Normal Keywords:
Cc: me@…, Sage Abdullah Triage Stage: Someday/Maybe
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

ContentType model is quite specific, so we could add the subclass of ForeignKey field with some specific features.

For example we have such model:

class ModelWithContentTypeField(models.Model):
    ct = ContentTypeField(on_delete=models.CASCADE)

In comparison with ForeignKey ContentTypeField will have these features:

  1. ModelWithContentTypeField.objects.first().ct will use content types cache.
  1. ContentTypeField will support lookups on the model classes:

ModelWithContentTypeField.objects.filter(ct=FooModel) vs ModelWithContentTypeField.objects.filter(ct=ContentType.objects.get_for_model(FooModel))

ModelWithContentTypeField.objects.filter(ct__in=[FooModel, BarModel]) vs
ModelWithContentTypeField.objects.filter(ct__in=[ContentType.objects.get_for_model(model) in [FooModel, BarModel]])

  1. Creation using a model class as a value:

ModelWithContentTypeField.objects.create(ct=FooModel)

Here's rough implementation.

Change History (8)

comment:1 by Sergey Fedoseev, 8 years ago

Owner: changed from nobody to Sergey Fedoseev
Status: newassigned

comment:2 by Jani Tiainen, 8 years ago

Does this feature require changes in Django core which prevents implementing this as an external app? I only saw quite small change in actual Django core.

comment:3 by Tim Graham, 8 years ago

Triage Stage: UnreviewedSomeday/Maybe

Sergey, could you write to the DevelopersMailingList to get feedback on the idea?

comment:4 by Adam Johnson, 8 years ago

Cc: me@… added

comment:5 by Marten Kenbeek, 8 years ago

Note that you shouldn't hardcode the ContentType class anywhere, or migrations will refer to the wrong model. Use self.related_model in the field, and self.field.related_model in the descriptor.

in reply to:  5 comment:6 by Sergey Fedoseev, 8 years ago

Replying to Marten Kenbeek:

Note that you shouldn't hardcode the ContentType class anywhere, or migrations will refer to the wrong model. Use self.related_model in the field, and self.field.related_model in the descriptor.

Thanks for the hint!

comment:7 by Sergey Fedoseev, 2 years ago

Owner: Sergey Fedoseev removed
Status: assignednew

comment:8 by Sage Abdullah, 3 months ago

Cc: Sage Abdullah added
Note: See TracTickets for help on using tickets.
Back to Top