Skip to content

Instantly share code, notes, and snippets.

@mike360 mike360/models.py
Last active Jun 11, 2019

Embed
What would you like to do?
Simple follower/following relationship in Django
$ ./manage.py 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.
(InteractiveConsole)
>>> from followers.models import *
>>> john = User.objects.create_user('john', 'lennon@thebeatles.com', 'password')
>>> paul = User.objects.create_user('paul', 'mccartney@thebeatles.com', 'password')
>>> george = User.objects.create_user('george', 'harrison@thebeatles.com', 'password')
>>> ringo = User.objects.create_user('ringo', 'starr@thebeatles.com', '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)
@coci

This comment has been minimized.

Copy link

commented May 22, 2019

what is the following in john.following.add(.....) ?

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.