我正在学习Django,并希望检索所有DON'T与我正在查看的当前对象有关系的对象。
这个想法是一个简单的Twitter模仿。
我正在想办法实现get_non_followers
。
from django.db import models
RELATIONSHIP_FOLLOWING = 1
RELATIONSHIP_BLOCKED = 2
RELATIONSHIP_STATUSES = (
(RELATIONSHIP_FOLLOWING, 'Following'),
(RELATIONSHIP_BLOCKED, 'Blocked'),
)
class UserProfile(models.Model):
name = models.CharField(max_length=200)
website = models.CharField(max_length=200)
email = models.EmailField()
relationships = models.ManyToManyField('self', through='Relationship',
symmetrical=False,
related_name='related_to')
def __unicode__ (self):
return self.name
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
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 get_non_followers(self):
# How to do this?
return
class Relationship(models.Model):
from_person = models.ForeignKey(UserProfile, related_name='from_people')
to_person = models.ForeignKey(UserProfile, related_name='to_people')
status = models.IntegerField(choices=RELATIONSHIP_STATUSES)
这不是特别吸引人,但它给出了正确的结果(刚刚测试):
def get_non_followers(self):
UserProfile.objects.exclude(to_people=self,
to_people__status=RELATIONSHIP_FOLLOWING).exclude(id=self.id)
简言之,使用exclude()
过滤掉当前用户后面的所有UserProfiles
,这将使用户自己(可能不应该包括在内)和所有用户不跟随他们。
实现get_non_followers
:的解决方案
def get_non_following(self):
return UserProfile.objects.exclude(to_person__from_person=self, to_person__status=RELATIONSHIP_FOLLOWING).exclude(id=self.id)
这个答案是OP Avi Meir在CC by-SA 3.0下发布的对在django中查找没有关系的对象问题的编辑。
current_userprofile = current_user.get_profile()
rest_of_users = Set(UserProfile.objects.filter(user != current_userprofile))
follow_relationships = current_userprofile.relationships.filter(from_person=current_user)
followers = Set();
for follow in follow_relationships:
followers.add(follow.to_person)
non_followeres = rest_of_users.difference(followers)
这里的non_followers
是您想要的用户配置文件列表。current_user
是您试图查找其non_followers
的user
。
我还没有测试过,但它认为它应该做你想做的事。
def get_non_followers(self):
return self.related_to.exclude(
from_people__to_person=self)
我已经搜索了一个小时的方法或方法,但一无所获。但有办法做到这一点。您可以简单地使用for循环来遍历所有对象,并删除所有具有特殊属性值的对象。这里有一个示例代码:
all_objects = className.objects.all()
for obj in all_objects:
if obj.some_attribute == "some_value":
all_objects.remove(obj)