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?
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: