如何创建未知数量的变量并将其保存到 Django 模型?

How do I create and save an unknown amount of variables to Django Model?

我正在通过 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 数据库,你可以使用 ArrrayField (https://docs.djangoproject.com/en/3.2/ref/contrib/postgres/fields/) 来制作一个字符串数组来表示 urls

b) 你可以使用与这个相关的辅助 table 并将 url 放在那里

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