Django - Can I use an abstract model in another model?

advertisements

I'm new to Django (and it's been a few years since I played with databases), and might be dancing around something simple that I don't know what to google.

Essentially, I want to have a table of "Events" which can contain data of various Types. Say one event is an "alarm" and another is a "message." The "alarm" type needs different fields than the "message" so it seems to make sense to not store the data in one big table containing any sort of data that might be needed for any event. However, I want to be able to get a list of all events for a given "event_block" foreign key.

I have done some reading about abstract models and proxies, etc, but I haven't been able to figure out how one Model can refer to an abstract model (if that is in fact the path to take).

models.py:

class Event(models.Model):
  #id auto-generated primary_key
  event_block = models.ForeignKey(Block, on_delete=models.CASCADE)
  event_data = BaseEvent  # This is wrong, but what is right?

class BaseEvent(Models.model):
  class Meta:
    abstract=True
  ... common event info ...

class AlarmEvent(BaseEvent):
  ... event info for alarms ...

class MessageEvent(BaseEvent):
  ... event info for messages ...

Ideally I would be able to, in my template, create a drop down box with all available event_types and then click a "submit" button the form to create that event (with its necessary event data fields) within my Event model and let Django handle the details of how that is handled in the database tables.

What am I missing?


Firstly, This is appropriate with the Event model

class Event(models.Model):
  event_block = models.ForeignKey(Block, on_delete=models.CASCADE)
  event_data = models.ForeignKey(BaseEvent)

However... BaseEvent with abstract=True does not physically exist but its children AlarmEvent and MessageEvent does. So I am not sure you can point BaseEvent as a ForeignKey. This post about generic foreign key may help.

Secondly about the structure of models. IMO, things can be simpler without abstract mother class. How about a model with category field?

CATEGORY = ( ('field1', 'field name 1'), ('field2', 'field name 2'), )
class Event(models.Model):
  category = models.CharField(max_length=10, choices=CATEGORY)
  # SOME OTHER FIELDS...

you can see a form of the model via django admin in default.