【问题标题】:How do I create and save an unknown amount of variables to Django Model?如何创建未知数量的变量并将其保存到 Django 模型?
【发布时间】:2021-11-24 05:05:57
【问题描述】:

我正在通过 tweepy 使用 twitter api,但我不确定如何将未知数量的媒体 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}
            )
    

【问题讨论】:

    标签: python django model


    【解决方案1】:

    我看到了两种可能的选择:

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

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

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

    【讨论】:

    • 我认为 ArrayField 是我正在寻找的。谢谢!
    猜你喜欢
    • 2011-11-22
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多