Skip to content Skip to sidebar Skip to footer

Finding Objects Without Relationship In Django

I am learning Django, and want to retrieve all objects that DONT have a relationship to the current object I'm looking at. The idea is a simple Twitter copycat. I am trying to fig

Solution 1:

This isn't particularly glamorous, but it gives correct results (just tested):

def get_non_followers(self):
    UserProfile.objects.exclude(to_people=self,
        to_people__status=RELATIONSHIP_FOLLOWING).exclude(id=self.id)

In short, use exclude() to filter out all UserProfiles following the current user, which will leave the user themselves (who probably shouldn't be included) and all users not following them.


Solution 2:

i'v been searching for a method or some way to do that for like an hour, but i found nothing. but there is a way to do that. you can simply use a for loop to iterate through all objects and just remove all objects that they have a special attribute value. there is a sample code here:

all_objects = className.objects.all()
for obj in all_objects:
    if obj.some_attribute == "some_value":
        all_objects.remove(obj)

Solution 3:

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)

Here non_followers is the list of userprofiles you desire. current_user is the user whose non_followers you are trying to find.


Solution 4:

I haven't tested this out, but it think it should do what you want.

def get_non_followers(self):
    return self.related_to.exclude(
    from_people__to_person=self)  

Post a Comment for "Finding Objects Without Relationship In Django"