What are some different ways to model a polymorphic relationship so it can easily be accessed in templates and keep things generally DRY?
I'll use a social platform as an example. A User can take a variety of different actions, make a post, update their status, etc. I'll call these Activities. I want to be able to access all of a user's activities from a user object. Many more activities exist, I'm looking for a DRY way to work with them using some sort of polymorphic strategy.
# ./models.py
class User(models.Model):
...
class Post(models.Model):
User = models.ForeignKey(User)
body = models.TextField()
...
class StatusUpdate(models.Model):
User = models.ForeignKey(User)
text = models.TextField()
Requirements
- Get a User's activities organized by activity type so I can neatly iterate over them from an HTML template.
I'm thinking something like this:
def user_activities(pk):
User = User.objects.get(pk)
activities = User.activities
...
return activities
{
'post': [{'body': 'My first post!'}, {'body': 'I love pineapple on pizza.'}],
'status_update': [{'text': 'Hello!'}, {'text': 'Camping for the week'}],
}
- Serialize a User and it's activities. Deserialize a User and it's activities into the correct DB models.
A user should be able to export and import their profile along with all their content.