Unable to set foreign keys for abstract models in Django. However, you can set foreign keys for a non-abstract base class. The only limitation is that the inverse relationship of the foreign key will return instances of the base class. You can get around this limitation using django-polymorphic .
Django Polymorphic allows you to query objects of the base class, but retrieves instances of the child class:
>>> Project.objects.create(topic="Department Party") >>> ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner") >>> ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter") >>> Project.objects.all() [ <Project: id 1, topic "Department Party">, <ArtProject: id 2, topic "Painting with Tim", artist "T. Turner">, <ResearchProject: id 3, topic "Swallow Aerodynamics", supervisor "Dr. Winter"> ]
To use polymorphic django, you only need to declare your models using the Polymorphic model as a base class:
from django.db import models from polymorphic.models import PolymorphicModel class ModelA(PolymorphicModel): field1 = models.CharField(max_length=10) class ModelB(ModelA): field2 = models.CharField(max_length=10) class ModelC(ModelB): field3 = models.CharField(max_length=10)
Foreign keys also return instances of the child classes that you need. I suppose:
Please note that these queries will be slightly less effective .
Sebastian wozny
source share