Why isn't count() working the way I expect in my code?
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 ve开发者_开发问答ry good, thank you
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.
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
len is the correct one for that case.
>>> a=[1,2,3,4]
>>> print len(a)
4
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.
精彩评论