Let's say I have the following parent models in my Django application:
class Location(models.Model):
name = models.CharField(max_length=100)
class Exit(models.Model):
location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="exits")
closed = models.BooleanField()
And two pairs of corresponding child models:
class Submarine(Location):
size = models.FloatField()
class Hatch(Exit):
diameter = models.FloatField()
class House(Location):
height = models.FloatField()
class Door(Exit):
width = models.FloatField()
height = models.FloatField()
In this setup it is possible for a House to have a Hatch as one of its Exits, as well as for a Submarine to have a Door. Is there a way to explicitly prevent this from happening? Ideally, I would like an exception to be thrown on attempt to set an invalid foreign key.
Moving the location field from Exit to Hatch and Door is not an option, because I want to be able to use constructions like the following:
open_locations = Location.objects.filter(exits__closed=False)
and avoid duplication (i.e. writing separate functions for Houses and Submarines).
Maybe the limit_choices_to constraint could be helpful, but I didn't manage to figure out how to apply it here.