Skip to content

Instantly share code, notes, and snippets.



Forked from mike360/
Created May 22, 2019
What would you like to do?
Simple follower/following relationship in Django
$ ./ shell
Python 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from followers.models import *
>>> john = User.objects.create_user('john', '', 'password')
>>> paul = User.objects.create_user('paul', '', 'password')
>>> george = User.objects.create_user('george', '', 'password')
>>> ringo = User.objects.create_user('ringo', '', 'password')
>>> john.following.add(Follower(following=paul))
>>> john.following.add(Follower(following=george))
>>> paul.following.add(Follower(following=john))
>>> ringo.following.add(Follower(following=john))
>>> ringo.following.add(Follower(following=paul))
>>> ringo.following.add(Follower(following=george))
>>> john.followers.all()
[<Follower: paul follows john>, <Follower: ringo follows john>]
>>> paul.followers.all()
[<Follower: john follows paul>, <Follower: ringo follows paul>]
>>> george.followers.all()
[<Follower: john follows george>, <Follower: ringo follows george>]
>>> john.following.all()
[<Follower: john follows paul>, <Follower: john follows george>]
>>> ringo.following.all()
[<Follower: ringo follows john>, <Follower: ringo follows paul>, <Follower: ringo follows george>]
>>> ringo.followers.all()
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Follower(models.Model):
follower = models.ForeignKey(User, related_name='following')
following = models.ForeignKey(User, related_name='followers')
class Meta:
unique_together = ('follower', 'following')
def __unicode__(self):
return u'%s follows %s' % (self.follower, self.following)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.