proposal: add special subclass of ForeignKey for storing ContentTypes

88 views
Skip to first unread message

Sergey Fedoseev

unread,
Apr 4, 2017, 4:46:31 PM4/4/17
to Django developers (Contributions to Django itself)
Hi all,

Some time ago I created 'new feature` ticket and Tim Graham asked me to write here to get some feedback on the idea. So here it is.

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


For example, we have a model:


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

In comparison with ForeignKey ContentTypeField will have these features:

  1. ModelWithContentType.objects.first().ct will use content types cache
  1. ContentTypeField will support lookups on the model classes (on model instances too?):
ModelWithContentType.objects.filter(ct=FooModel) vs.

ModelWithContentType.objects.filter(ct=ContentType.objects.get_for_model(FooModel))


ModelWithContentType.objects.filter(ct__in=[FooModel, BarModel]) vs.
ModelWithContentType.objects.filter(ct__in=[ContentType.objects.get_for_model(model) in [FooModel, BarModel]])
  1. Creation using a model class as a value (not sure if it's useful actually):

ModelWithContentType.objects.create(ct=FooModel)


Here's rough implementation.

Asif Saifuddin

unread,
Apr 5, 2017, 1:24:31 AM4/5/17
to Django developers (Contributions to Django itself)
Hi Sergey,

I was also wondering why GenericForeignKey don't have direct subclass of ForeignKey while writing a dep about field API improvement. Though I am not 100% sure your implementation.

Thanks for bringing it up.

Adam Johnson

unread,
Apr 5, 2017, 12:06:12 PM4/5/17
to django-d...@googlegroups.com
Sergey, I like the idea. It at least serves as a demonstration of what can be done with custom fields. The PoC shows it's not too much code either. Would you be looking to replace the existing FK's to ContentType too, e.g. in Admin and Auth?

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscribe@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/0764f9bc-be05-47ac-8201-b419a93d3061%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
Adam
Reply all
Reply to author
Forward
0 new messages