Skip to content

Instantly share code, notes, and snippets.

@mmalone
Created September 1, 2009 20:13
Show Gist options
  • Save mmalone/179347 to your computer and use it in GitHub Desktop.
Save mmalone/179347 to your computer and use it in GitHub Desktop.
class FollowerDescriptor(object):
"""
A descriptor which provides access to a user's followers.
"""
def __get__(self, instance, cls):
if not instance:
raise AttributeError('Manager must be accessed via instance')
class RelationshipManager(models.Manager):
def get_query_set(self):
return User.objects.filter(following_relationships__to_user=instance)
def add(self, user):
raise NotImplementedError("Can't add a follower. Add user to the people the related user is following instead")
def remove(self, user):
raise NotImplementedError("Can't remove a follower. Remove user from people the related user is following instead")
return RelationshipManager()
class FollowingDescriptor(object):
"""
A descriptor which provides access to users's a user is following.
"""
def __get__(self, instance, cls):
if not instance:
raise AttributeError('Manager must be accessed via instance')
class RelationshipManager(models.Manager):
def get_query_set(self):
return User.objects.filter(follower_relationships__user=instance)
def add(self, user):
instance.following_relationships.create(to_user=user)
def remove(self, user):
try:
relationship = instance.following_relationships.get(to_user=user)
relationship.delete()
except ObjectDoesNotExist:
pass
return RelationshipManager()
from django.contrib.auth.models import User
class Relationship(models.Model):
user = models.ForeignKey(User, related_name='following_relationships')
to_user = models.ForeignKey(User, related_name='follower_relationships')
reciprocal = models.BooleanField(default=False)
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = (('user', 'to_user'))
setattr(User, 'following', managers.FollowingDescriptor())
setattr(User, 'followers', managers.FollowerDescriptor())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment