一旦用户在search_text
中输入HashtagSearch FormView
,函数get_tweets()
将从Twitter获得与该标签相关的位置。
然后,使用get_or_create
将search_text
保存在Hashtag
数据库中。然后,逐行浏览txt文件,并假设已满足正则表达式要求,则将该行添加为与数据库中的locations
关联的search_text
。
工作流程的摘要:
search_text
中输入HashtagSearch FormView
,HashtagSearch FormView
中运行了一个功能,该功能使用search_text
作为主题标签(“适用的推文”)在Twitter上搜索推文,locations
模型中的search_text
关联的Hashtag
对象中。location
模型中的search_text
关联的Hashtag
对象渲染 results.html 。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()
答案 0 :(得分:2)
get_or_create
方法返回元组(obj, created)
而不是仅返回对象。这样,您可以检查是否已检索或创建对象。
只需按以下步骤打开元组的包装:
tweet_object, created = Hashtag.objects.get_or_create(search_text=search_filter)
tweet_object.locations.create(valid_tweet_location)
答案 1 :(得分:2)
您在此处发布了太多代码-追溯显示了发生错误的位置,您应该刚刚发布了get_tweets
方法。
错误确实在那儿发生。这是因为get_or_create
返回的是元组-也就是说,它返回对象和一个布尔值,显示该对象是否是创建的。既然您不在乎,您可以将其分配给一个被忽略的变量:
tweet_object, _ = Hashtag.objects.get_or_create(search_text=search_filter)