Reputation: 288
I'm developing kind of a social network in Django, but I don't see the way to maintain coupled my models.
I have a model User
, which can comment on other Users, Pics, Pages (capitals are because they're models) via a Comment
model. In order to arrange all that comments I created the Board model, that has one owner and receives all the comments addresed to that owner. The problem is I don't know how is its owner, i.e., which model does it belong to. It could be a pic's board, but also a user's one. So I end up with a model like this:
class Board(models.Model):
category = models.IntegerField()
owner_id = models.IntegerField()
I store owner's id and owner's category to be able to perform other tasks, but this solution doesn't convince me at all. A friend has advised me to use an abstract class Board
, and then create a UserBoard
, PicBoard
, PageBoard
which inherit from Board
, but I think that will be useless too. I've thought about GenericRelations
, but I'm not sure if that is the correct way to achieve what I'm trying. Any proposal will be listened and considered, thanks for your help :)
PS: Oh, and sorry if the title isn't very descriptive, but I couldn't figure out a better one. It's hard to explain this problem
Upvotes: 2
Views: 3759
Reputation: 49816
Create a class BoardOwner
. Have all models which have a board inherit from that, and have the board have a foreignkey relationship with BoardOwner
. You'll need to then scan over the various childlinks to figure out which one is the "real" child. This more fiddly, but localises all of the complexity in one class.
Have a foreignkey from each class that has a board to the board. If you always have boards enter your system via a method on the owner (as opposed to a query on Board
or elsewhere), you can have code in the owner which lets the Board
know which foreign key reverse relationship to use. You'll probably want to factor that code into its own class.
Use contenttypes
: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
This wraps up this sort of thing.
Upvotes: 3