Reputation: 55
In my project, I currently have two different post types (but in the future they could be more): Posts and Reviews. Both can be commented, so they could share the same Comment model.
The problem is: if I create two different apps for Post and Review (and eventually other post types), should I share the same Comment model with a GenericForeignKey or should I recreate in each app the same Comment model with a specific ForeignKey? Or maybe I just should put every post type in a unique common app?
Upvotes: 2
Views: 644
Reputation: 6858
I would set it up in one of the following ways.
Easy solution: use when needed
Directory (app) structure:
post
models.py
review
models.py
common
models.py
In common/models.py
, you then define the comment:
class Comment(models.Model):
title = models.CharField(max_length=128, blank=True, default='')
...
In post/models.py
, you then refer to this class whenever you need it:
from common.models import Comment
class Post(models.Model):
comment = models.ForeignKey(Comment, related_name='comments')
...
Generic solution: mixins
Another option is to create a mixin behavior inside your common app.
class Commentable(models.Model):
comment = models.ForeignKey(Comment, related_name='comments')
And mix this behavior in by inheriting from it.
from common.models import Commentable
class Post(Commentable, models.Model):
...
You should read a bit about mixins before using them all over the place though.
Upvotes: 2
Reputation: 348
As another option, you can check django-polymorphic. https://django-polymorphic.readthedocs.io/en/stable/
Upvotes: 0