我如何创建和保存未知数量的变量到Django模型?



我正在通过tweepy使用twitter api,我不确定如何将未知数量的媒体url保存到模型对象

媒体部分是我卡住的地方。有些推文会有媒体url,有些则不会,而有些可能会有大量的媒体url。

我如何创建未知数量的媒体url变量,然后我如何将其添加到update_or_create?

我非常感谢你的帮助……我一直在想办法解决这个问题。
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}
)

我看到两个可能的选项:

a)如果你使用的是PostgreSQL数据库,你可以使用arrayfield (https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/fields/)来创建一个字符串数组,表示url

b)您可以使用与此表相关的辅助表并将url放在那里

我有时使用第一个(但仅限于Postgres),有时使用第二个(这在关系数据库中更有意义)

最新更新