I am working with the twitter api via tweepy and I am unsure how to save an unknown quantity of media urls to a model object.
The media section is where I am stuck. Some tweets will have media urls and some wont, while some may have numerous media urls.
How do I create an unknown amount of media url variables and then how do I add that to the update_or_create?
I appreciate all your help... been trying to figure this out for awhile now.
user = api.get_user(screen_name=team)
timeline = tweepy.Cursor(
api.user_timeline, id=team, exclude_replies=True,
include_rts=False).items(20)
handle = user['screen_name']
location = user['location']
description = user['description']
for tweet in timeline:
tweet_id = tweet['id']
date = tweet['created_at']
content = tweet['text']
`This is where I am stuck`
if 'media' in tweet.entities:
for media in tweet.extended_entities.media:
url = media['media_url']
Tweets.objects.update_or_create(
tweet_id=tweet_id, defaults={
'handle': handle,
'tweet_id': tweet_id,
'location': location,
'description': description,
'date': date,
'content': content,
'url': url}
)
CodePudding user response:
I see two possible options:
a) if you are using PostgreSQL database you can use ArrrayField (https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/fields/) to make an array of strings representing urls
b) you can use secondary table that has relation to this one and put urls there
I sometimes use first one (but it is limited to Postgres) and sometimes the second one (which does make more sense in relation database)