目标
一旦用户在search_text中输入HashtagSearch FormView,函数get_tweets()将从Twitter中获得与该标签相关联的位置。
然后,使用get_or_create将search_text保存在Hashtag db中。然后,逐行遍历txt文件,假设regex要求得到满足,将该行添加为与db中的locations相关联的search_text。
作为工作流程的摘要:
search_text中输入HashtagSearch FormView,HashtagSearch FormView中运行一个函数,它使用search_text作为标签搜索Twitter中的tweet(“适用的tweet”),locations模型中的search_text相关联的Hashtag对象。search_text关联的location对象呈现Hashtag。错误
Request Method: POST
Django Version: 2.0
Exception Type: AttributeError
Exception Value: 'tuple' object has no attribute 'locations'
Exception Location: /mnt/project/mapping_twitter/views.py in get_tweets, line 87
Python Executable: /mnt/data/.python-3.6/bin/python
Python Version: 3.6.5
Python Path:
['/mnt/project',
'/mnt/data/.python-3.6/lib/python36.zip',
'/mnt/data/.python-3.6/lib/python3.6',
'/mnt/data/.python-3.6/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6',
'/mnt/data/.python-3.6/lib/python3.6/site-packages']代码
views.py
def get_tweets(self, form):
""" Get tweets from the Twitter API and store them to the db """
consumer_key = '...'
consumer_secret = '...'
access_token = '...'
access_secret = '...'
t = Twython(
app_key=consumer_key,
app_secret=consumer_secret,
oauth_token=access_token,
oauth_token_secret=access_secret,
)
# set to the text entered by User in Form
search_filter = self.request.POST.get('search_text')
# set the filter for hashtag and quantity
search = t.search(q='#{}'.format(search_filter), count=50)
tweets = search['statuses']
f = open('tweet_locations.txt', 'w+')
for tweet in tweets:
if tweet['user']['location']:
tweet_location = tweet['user']['location']
f.write("{}\n".format(tweet_location))
f.close()
data = open('tweet_locations.txt', 'r')
# Regex out 'unmappable' locations
valid_ex = re.compile(r'[A-Z][a-z]+, [A-Za-z]+')
for line in data:
valid_tweet_location = str(valid_ex.search(line))
if valid_tweet_location:
# ISSUE: save the locations_list to the Hashtag model as the locations associated with the search_text entered
tweet_object = Hashtag.objects.get_or_create(search_text=search_filter)
# necessary as locations is a M2M object
tweet_object.locations.create(valid_tweet_location)
data.close()发布于 2018-07-03 07:15:31
get_or_create方法返回元组(obj, created),而不是仅返回对象。通过这种方式,您可以检查对象是否被检索或创建。
只需按以下方式解压缩元组:
tweet_object, created = Hashtag.objects.get_or_create(search_text=search_filter)
tweet_object.locations.create(valid_tweet_location)发布于 2018-07-03 07:17:07
您在这里发布了太多的代码--回溯显示了错误发生在哪里,您应该只发布get_tweets方法。
这个错误确实发生在那里。这是因为元组是由get_or_create返回的--也就是说,它返回对象和一个布尔值,如果它是一个创建的话。由于您不关心这个问题,所以只需将其赋值给一个被忽略的变量:
tweet_object, _ = Hashtag.objects.get_or_create(search_text=search_filter)https://stackoverflow.com/questions/51148513
复制相似问题