Book Image

Learning Website Development with Django

Book Image

Learning Website Development with Django

Overview of this book

Table of Contents (18 chapters)
Learning Website Development with Django
Credits
About the Author
About the Reviewers
Preface
Index

Building Friend Networks


One important aspect of socializing in our application is letting users maintain their friend lists and browse the bookmarks of their friends. So in this section we will build a data model to maintain user relationships, and then program two views to enable users to manage their friends and browse friend bookmarks.

Creating the Friendship Data Model

Let's start with the data model for the friends feature. When a user adds another user as a friend, we need to maintain both users in one object. Therefore, the Friendship data model will consist of two references to the User objects involved in the friendship relationship. Create this model by opening bookmarks/models.py and inserting the following code in it:

class Friendship(models.Model):
  from_friend = models.ForeignKey(
    User, related_name='friend_set'
  )
  to_friend = models.ForeignKey(
    User, related_name='to_friend_set'
  )
  def __str__(self):
    return '%s, %s' % (
      self.from_friend.username,
  ...