0

My main task is to implement likes and comments in django application, but I have concerns regarding model structure and overall architecture of application.

What I want to achieve:

Basically I have only two models (for example Book and Author), which I want to be liked, shared and commented. So obviously, I need to create corresponding tables. The question is, how will be better to reference each Like, Share and Comment in Book and Author rows.

1-st solution: The first thing which came in mind is just to add corresponding ForeignKeys in Like, Share and Comment which will point to Author and Book. So, for example Like table will be in next form:

|---------|-----------|-----------|
|   ID    | AUTHOR_ID |  BOOK_ID  | 

Where ID is id of Like, AUTHOR_ID and BOOK_ID are ForeignKeys to Author and Book rows.

The problem of this solution is that if you want to add ability to 'like' more stuff you will need to add new columns to Like table. I think this solution is hacky, since Like table can grow up very quickly.

2-nd solution: I have read this question where solution suggested to create a parent table, which can be liked and then inherit from it Book and Author tables.

This solution seems very nice to me, but now concern is about concrete inheritance in Django ORM. In book Two scoops of Django authors recommend to avoid it almost everywhere.

Could you please help me with advice, whether or not should I choose Multitable (Concrete) Inheritance in order to achieve what I want? Or maybe another, more beatiful and clean solution?

Thanks

Community
  • 1
  • 1
Araz Abishov
  • 1,661
  • 3
  • 15
  • 26

1 Answers1

3

This is exactly the sort of problem that generic relations were created to solve. The documentation on that link describes a tagging system, but it can just as easily be applied to likes.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks for reply. I have read several articles on GenericForeignKeys and it seems that they are limited in filtering. For example: if I need to filter likes by content_type, will I be able to do that? – Araz Abishov Nov 08 '14 at 17:22
  • Of course, since content_type is a field on the Like model itself. What you can't do easily is filter by something on the destination models, ie Book and Author, which makes sense because you can't know in advance whether or not the related object even has that attribute. – Daniel Roseman Nov 08 '14 at 17:26