I'm specifically asking about Django here, but I'd appreciate any insight.
I'm currently writing up a basic social network. My plan is to allow users to make different kinds of posts (ie text posts, image posts, and video posts) and then allow them to access others' posts chronologically on their feed. The feed needs to contain all of these different kinds of posts.
I assumed that this would be trivial to do, by subclassing a general Post class into a TextPost class, an ImagePost class, and so on, then simply displaying each post on the feed.
#What I thought I would do class Post(models.Model): user = models.ForeignKey(User, editable = False) time = models.TimeField(auto_now=True) class TextPost(Post): content = models.TextField() class ImagePost(Post): image = models.ImageField()
However, it doesn't look like Django is built to handle this; when I try to get a list of Posts, Django returns the posts without the subclass fields, ie without the "content" or "image" fields.
As I see it, I have two choices:
- Add more fields to the Post class, so it contains "content", "image", "post", etc. I know that this is bad, since it would mean that many Post rows would be empty, it wouldn't scale to allow many different post types, and it would require a lot more code to make sure that, ie, a single Post didn't have both an image and a video.
- Use a workaround such as this InheritanceManager class to do what I want, despite what Django allows. Though I'm currently going ahead with this option since it does what I want to do, I'm leery of it since it seems strange that Django doesn't handle what seems to me to be a common issue (treating slightly different sibling models the same way) very simply, and I feel as though I've gone wrong somewhere.
To put it shortly, I want to display all of these slightly different subclasses of the same model in a list, and I don't know how to do it properly. I know that this question seems a bit subjective, but, at least to me, this problem just feels like it should have an obvious solution.