tags:

views:

138

answers:

4
class FriendshipManager(models.Manager):    
       def are_friends(self, user1, user2):
            if self.filter(from_user=user1, to_user=user2).count() > 0:
                return True
            if self.filter(from_user=user2, to_user=user1).count() > 0:
                return True
            return False

and i found count() so i try it, but it runs wrong

a=[1,2,3,4]
print a.count()

or

a='ssada'
print a.count()

why my code run wrong,but the FriendshipManager can run ,thanks Please try to use the code, rather than text, because my English is not very good, thank you

+5  A: 

I think you want to use len(a) rather than a.count() if you want to determine the length/size of the list. a.count() actually requires an argument anyway. It counts the number of occurrences of a value. For example:

a = [2, 6, 2, 1, 5, 3, 9, 5]
print a.count(5) #should display 2 because there are two elements with a value of 5
print a.count(3) #should display 1 because there is only one element with a value of 3
Dustin
+3  A: 

len is the correct one for that case.

>>> a=[1,2,3,4]
>>> print len(a)
4
S.Mark
+8  A: 

The issue here is that you've mixed up two methods with the same name.

On a sequence in Python, count() works exactly has Dustin describes to "count the number of occurrences of the parameter in the sequence."

The code you're referencing however, is from a Django model. There, calling count() on the filter object is an alias for the SQL grouping function COUNT, which sums up the number of matching rows.

In essence, the count in your initial example and the count in the two examples after that aren't the same method at all.

Travis Bradshaw
+1 The part about the SQL `COUNT` is an important difference
T. Stone
+1 This is very obviously the correct answer.
Omnifarious
High five for completeness!
jathanism
thanks ,you are right!
zjm1126
Glad I could help. If this is your preferred answer, would you mind clicking the checkmark to mark it as so? Thanks!
Travis Bradshaw
A: 

I am not sure if this is a right answer, but, try this instead of the Model Manager code which you have. No big changes as such ofcourse.

class FriendshipManager(models.Manager):    
   def are_friends(self, user1, user2):
        if self.filter(from_user=user1, to_user=user2).count() or self.filter(from_user=user2, to_user=user1).count():
            return True
        return False

If count() returns a value other than zero, it will always return True.

Maddy