Opened 2 years ago

Last modified 20 months ago

#27580 assigned New feature

add special field for storing content types

Reported by: Sergey Fedoseev Owned by: Sergey Fedoseev
Component: contrib.contenttypes Version: master
Severity: Normal Keywords:
Cc: me@… 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 (6)

comment:1 Changed 2 years ago by Sergey Fedoseev

Owner: changed from nobody to Sergey Fedoseev
Status: newassigned

comment:2 Changed 2 years ago by Jani Tiainen

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 Changed 2 years ago by Tim Graham

Triage Stage: UnreviewedSomeday/Maybe

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

comment:4 Changed 20 months ago by Adam (Chainz) Johnson

Cc: me@… added

comment:5 Changed 20 months ago by 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.

comment:6 in reply to:  5 Changed 20 months ago by Sergey Fedoseev

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!

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