Following users like twitter in Django, how would you do it?

database-design, django, django-models, python, twitter

Solution

First, you should understand how to store additional information about users. It requires another model that has a relation to one user, the "profile" model.

Then, you could use an M2M field, assuming you'd use django-annoying, you could define your user profile model as such:

from django.db import models

from annoying.fields import AutoOneToOneField

class UserProfile(models.Model):
    user = AutoOneToOneField('auth.user')
    follows = models.ManyToManyField('UserProfile', related_name='followed_by')

    def __unicode__(self):
        return self.user.username

And use it as such:

In [1]: tim, c = User.objects.get_or_create(username='tim')

In [2]: chris, c = User.objects.get_or_create(username='chris')

In [3]: tim.userprofile.follows.add(chris.userprofile) # chris follows tim

In [4]: tim.userprofile.follows.all() # list of userprofiles of users that tim follows
Out[4]: [<UserProfile: chris>]

In [5]: chris.userprofile.followed_by.all() # list of userprofiles of users that follow chris
Out[5]: [<UserProfile: tim>]

Also, note that you could check / reuse apps like django-subscription, django-actstream, django-social (harder to use probably)...

You might want to take a look at the django packages for notifications and activities as they all require some follow/subscription database design.

Problem

I am playing with relationships in Django/python and I am wondering how you guys would create a relationship between a User and his followers and a Follower to the users he follows. Would love to read your opinion...

Original source

Related problems