代码:
other_users=User.objects.filter(logged_in=False)
for other_user in other_users:
other_posts=Post.objects.filter(author=other_user)
print('[!] Collecting other_posts from other_user => {} [{}] [!]'.format(other_user,other_posts))
try:
for other_post in other_posts:
print('[=] other_post: {}'.format(other_post))
if other_post.likes==0:
print('[=] other_post with 0 likes: {}'.format(other_post))
for like in range(max_likes_per_user):
rand_post=random.choice(other_posts)
print('[+] Random post => {} : TYPE[{}]'.format(rand_post,type(rand_post)))
post_index=other_posts.index(rand_post)
print('[!] Post index: {}'.format(post_index))
other_posts.pop(post_index)
print('[+] Liking {} POST'.format(rand_post))
rand_post.likes+=1
rand_post.save()
print('[!] Saving like [!]')
except Exception as e:
print('[-] Error: [-]\n\n'.format(e))
done=True
我试图弄清楚过去1小时的问题所在,仍然无法找到。
我试图从列表中获取随机选择的索引,但每当我到达该部分时,程序都会以空错误退出。
部分:
post_index=other_posts.index(rand_post)
print('[!] Post index: {}'.format(post_index))
之后的任何内容都没有返回任何内容,并且直接跳到Exception,但是,e变量总是为空,我没有得到错误输出。
我想知道为什么post_index变量没有获取任何数据,为什么它会跳到Exception部分。代码中看起来有什么坏处?
这些是我得到的输出:
[!] Collecting other_posts from other_user => Robot Tyler 1 [<QuerySet [<Post: Robot Tyler 1 - Title 1>, <Post: Robot Tyler 1 - Title 2>, <Post: Robot Tyler 1 - Title 3>, <Post: Robot Tyler 1 - Title 4>]>] [!]
[=] other_post: Robot Tyler 1 - Title 1
[=] other_post with 0 likes: Robot Tyler 1 - Title 1
[+] Random post => Robot Tyler 1 - Title 4 : TYPE[<class 'person.models.Post'>]
[-] Error: [-]
[!] Collecting other_posts from other_user => Robot Tyler 2 [<QuerySet [<Post: Robot Tyler 2 - Title 1>, <Post: Robot Tyler 2 - Title 2>, <Post: Robot Tyler 2 - Title 3>]>] [!]
[=] other_post: Robot Tyler 2 - Title 1
[=] other_post with 0 likes: Robot Tyler 2 - Title 1
[+] Random post => Robot Tyler 2 - Title 1 : TYPE[<class 'person.models.Post'>]
[-] Error: [-]
任何人都可以告诉我错误在哪里?
答案 0 :(得分:0)
出于某种原因,other_posts
变量为QuerySet
而不是列表。所以我所做的就是将其转换为list(other_posts)
。如果有人似乎理解other_posts
作为QuerySet
处理的原因,请在评论中解释。
这就是代码现在的样子:
other_users=User.objects.filter(logged_in=False)
for other_user in other_users:
other_posts=Post.objects.filter(author=other_user)
print('[!] Collecting other_posts from other_user => {} [{}] [!]'.format(other_user,other_posts))
try:
for other_post in other_posts:
print('[=] other_post: {}'.format(other_post))
if other_post.likes==0:
print('[=] other_post with 0 likes: {}'.format(other_post))
for like in range(max_likes_per_user):
rand_post=random.choice(other_posts)
print('[+] Random post => {} : TYPE[{}]'.format(rand_post,type(rand_post)))
post_index=list(other_posts).index(rand_post)
print('[!] Post index: {}'.format(post_index))
list(other_posts).pop(post_index)
print('[+] Liking {} POST'.format(rand_post))
rand_post.likes+=1
rand_post.save()
print('[!] Saving like [!]')
except Exception as e:
print(e)
done=True