Created
December 1, 2020 08:42
-
-
Save mentix02/016cb4f9e121685ce985149fced20dc8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import annotations | |
from django.db import models | |
from django.contrib.auth.models import AbstractUser | |
class FollowRequest(models.Model): | |
to_follow = models.ForeignKey( | |
'user.User', on_delete=models.CASCADE, related_name='requests' | |
) | |
requester = models.ForeignKey( | |
'user.User', on_delete=models.CASCADE, db_index=False, related_name='+' | |
) | |
def accept(self) -> None: | |
self.requester.follow(self.to_follow, force=True) | |
self.delete() | |
def reject(self) -> None: | |
self.delete() | |
def __str__(self) -> str: | |
return f'{self.requester} -> {self.to_follow}' | |
class User(AbstractUser): | |
PRIVATE = True | |
PUBLIC = False | |
VISIBILITY_CHOICES = [ | |
(PRIVATE, 'Private'), | |
(PUBLIC, 'Public'), | |
] | |
visibility: bool = models.BooleanField(default=PUBLIC, choices=VISIBILITY_CHOICES) | |
bio: str = models.CharField( | |
max_length=250, null=True, blank=True, help_text='About the user.' | |
) | |
picture = models.ImageField( | |
null=True, | |
blank=True, | |
default='default.png', | |
upload_to='profile_pictures', | |
verbose_name='profile picture', | |
) | |
_follows = models.ManyToManyField('User', blank=True, related_name='followed_by') | |
def unfollow(self, user: User) -> None: | |
""" Helper function to remove a user from this users following list. """ | |
self._follows.remove(user) | |
def follow(self, user: User, force: bool = False) -> None: | |
""" Helper function to add user to a follower list. """ | |
if user.id == self.id: | |
return | |
if force: | |
self._follows.add(user) | |
return | |
if user.visibility == User.PRIVATE: | |
FollowRequest.objects.get_or_create(requester=self, to_follow=user) | |
else: | |
self._follows.add(user) | |
def tweet_count(self) -> int: | |
return self.tweets.count() | |
def follower_count(self) -> int: | |
return self.followers.count() | |
def following_count(self) -> int: | |
return self.following.count() | |
@property | |
def following(self) -> models.QuerySet: | |
""" Returns a QuerySet of Users that this user follows. """ | |
return self._follows.all() | |
@property | |
def followers(self) -> models.QuerySet: | |
""" Returns a QuerySet of Users following this user. """ | |
return self.followed_by.all() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment