I've got a situation where I'm modelling a football match, and each match has a set of events related to it, that relate to what happened during the game. So something a bit like this:
class Event(models.Model):
time = models.IntegerField()
class Meta:
abstract = True
class Goal(Event):
scorer = models.ForeignKey('Player')
class PitchInvasion(Event):
number_of_people = models.IntegerField()
class FootballMatch(models.Model):
events = models.ForeignKey('Event')
Forgive the far fetched example, but it's there to show that these subclasses of Event
could be anything. What I then want to do is to be able to query all those events and order them on time, to give a chronological view of what happened in that match.
However, with abstract = True
, the Event
objects end up with a pitchinvasion_set
, goal_set
and so on, . Would this be solved by setting abstract = False
and using concrete inheritance? I've read that doing this is a bad idea, as it introduces an extra join.
What's the best way to deal with situations like this?
I agree with Peter Rowell's comment - model inheritance isn't what you think it is, and in my opinion is very rarely useful.
A much better way to approach this is with generic relations. So you'd have a Match
model, with an events = GenericRelation()
, and each of the Event types has a GenericForeignKey
back to Match. Then you could do match.events.all()
and get all the separate events for that match.
If you like, you can still use abstract inheritance for the base class for the events, if they do all share some fields such as description and time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With