I've pored over the Django docs regarding the contenttypes framework several times, and I simply don't understand it well enough to implement generic relations in my project. I've looked for online examples or tutorials regarding the matter, but I can't find a single one. Call me dumb, but I need some help on this one (please don't answer by simply linking to the docs). Based on the lack of resources online, I believe if you answer this question with a thorough example, your answer may be the most helpful example online to date regarding django generic relations (bonus!).
So, my question is: can someone show a simple example of the models and maybe a couple lines of code showing how to interact with instances of a generic model?
As inspiration, here is what I believe would be a very common situation:
A site has media items that are largely treated the same, but are slightly different. For example, let's say there are image and video items, and users can "like" an item or "comment" on an item. The likes and comments should be treated the same, regardless of whether they are posted on an image or video item. So, if there is an ItemView for viewing an image or a video in a user's album, the following kinds of calls would be possible : mediaitem.comments.all()
or len(mediaitem.likes.all())
or comment.user_who_commented
, without having to know which kind of media item it is (image or video).
I believe you would need six models for this:
- Abstract
MediaItem
class - Two different types of media item:
ImageItem
andVideoItem
- Abstract
MediaItemActions
class - Two different types of actions that can be done towards media items:
Like
andComment
If you know how to use this Django feature, please show us a full example! I feel like it would be an extremely powerful tool and am aching to use it in my application. The more explicit, the better.