Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Models for user, like, page like situation

I have a model for users and another for page. Now I want to implemented something like Facebook's like. A user can like any page. Later I have to retrieve a list of all likes by a single user and also a list of all users who have liked a particular page.

I tried with making a separate model for Likes and making two fields as User (OneToOne) and Page(OnetoOne). But how would I get the data later on?

like image 222
karambir Avatar asked Dec 21 '25 00:12

karambir


1 Answers

user = User.objects.get(username="foo")
user_likes = user.likes_set.all()

page = Page.objects.get(id=4)
page_likes = page.likes_set.all()

You can change the default name of the related manager in the definition of the fields in your Like model:

user = models.ForeignKey(User, related_name="likes")
page = models.ForeignKey(Page, related_name="likes")

And you can then call them like:

user_likes = user.likes.all()
page_likes = page.likes.all()

As a side note, there are a few Django apps out there that could do that job:

  • Django-Voting: Like application in django
  • Phileo, under the Pinax project: https://github.com/eldarion/phileo
like image 56
AJJ Avatar answered Dec 23 '25 14:12

AJJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!