0

In Django, how can I create a model that belongs to several models without having to create a foreign key field for each model?

Example: An Observation model that is related to any model that can be Observable (Request, Document, Quiz, etc).

I've tried contenttypes and it works fine in the shell but I've had problems working with serializers in django rest framework and I'd like to know if there's another way to do it or some package that is useful.

Thank you.

Martin Urbanec
  • 426
  • 4
  • 11
  • Did you mean you tried the generic foreign key in Django? Also have you looked at restframework about generic relationship? https://www.django-rest-framework.org/api-guide/relations/#rest-framework-generic-relations – James Lin Sep 29 '20 at 23:07
  • Are you looking for something like this? https://github.com/denisorehovsky/django-rest-polymorphic – David Sigley Aug 23 '23 at 19:34

1 Answers1

0

I'm not sure what you mean exactly - do you want to tie a model to several models at once? Then a foreign key is the best way forward.

If you want to allow any of the several models to be used, contenttypes seems like a good idea - if rest framework breaks, I recommend you to write a custom serializer, and use a serializers.SerializerMethodField there, see Django REST Framework: adding additional field to ModelSerializer for more details.

Martin Urbanec
  • 426
  • 4
  • 11