1 回答

TA貢獻1818條經驗 獲得超11個贊
我沒有找到一個簡單的解決方案,不需要額外的模型。這是我所做的:
Person(models.Model)如果您有類似的CustomUser(AbstractUser)實現,則不需要創建。否則Person,類在許多情況下都很有用。
count_函數非常有用,但對于大多數用例來說不是必需的。
在里面accounts/models.py我補充說:
RELATIONSHIP_FOLLOWING = 1
RELATIONSHIP_BLOCKED = 2
RELATIONSHIP_STATUSES = (
(RELATIONSHIP_FOLLOWING, 'Following'),
(RELATIONSHIP_BLOCKED, 'Blocked'),
)
class Person(models.Model):
relationships = models.ManyToManyField('self', through='Relationship',
symmetrical=False,
related_name='related_to')
def get_relationships(self, status):
return self.relationships.filter(
to_people__status=status,
to_people__from_person=self)
def get_related_to(self, status):
return self.related_to.filter(
from_people__status=status,
from_people__to_person=self)
def get_following(self):
return self.get_relationships(RELATIONSHIP_FOLLOWING)
def get_followers(self):
return self.get_related_to(RELATIONSHIP_FOLLOWING)
def count_following(self):
return len(self.get_relationships(RELATIONSHIP_FOLLOWING))
def count_followers(self):
return len(self.get_related_to(RELATIONSHIP_FOLLOWING))
def get_friends(self):
return self.relationships.filter(
to_people__status=RELATIONSHIP_FOLLOWING,
to_people__from_person=self,
from_people__status=RELATIONSHIP_FOLLOWING,
from_people__to_person=self)
def count_friends(self):
return len(self.get_friends())
class Relationship(models.Model):
from_person = models.ForeignKey(Person, related_name='from_people', on_delete=models.CASCADE)
to_person = models.ForeignKey(Person, related_name='to_people', on_delete=models.CASCADE)
status = models.IntegerField(choices=RELATIONSHIP_STATUSES)
def add_relationship(self, person, status):
relationship, created = Relationship.objects.get_or_create(
from_person=self,
to_person=person,
status=status)
return relationship
def remove_relationship(self, person, status):
Relationship.objects.filter(
from_person=self,
to_person=person,
status=status).delete()
return
添加回答
舉報