【问题标题】:How to build a django model to store twitter conversations?如何建立一个 django 模型来存储 twitter 对话?
【发布时间】:2020-08-18 14:41:33
【问题描述】:

我正在构建一个工具,用于获取用户时间线推文及其响应,我需要了解如何将这些对话存储在数据库中,然后在模板中呈现它们。

为了进行对话,我使用了一个 while 循环,它获取推文的“in_reply_to_status_id”,然后通过 id 检索此回复的状态对象,找到它的“in_reply_to_status_id”等,直到检索到整个对话。

这是我使用的代码:

conversation = []

while True:

    response = api.get_status(id=tweet_id, tweet_mode='extended')._json

    if response['in_reply_to_status_id'] == None:
        break
    else:
        message_dict = {}
        message_dict['author'] = response['user']['screen_name']
        message_dict['text'] = response['full_text']
        message_dict['created_at'] = response['created_at']
        message_dict['author_profile_url'] = response['user']['profile_image_url']
        conversation.append(message_dict)
        tweet_id = response['in_reply_to_status_id']

if len(conversation) == 0:
    return None

return reversed(conversation)

在我的 models.py 中,我有一个 Tweet 模型,我需要了解如何制作一个模型来存储上面脚本检索到的整个对话/对话/线程。此外,之后应该可以将对话呈现为简单的聊天对话。

我的第一个想法是在我的推文模型中添加“回复”字段并将对话存储为 JSON,但这对我来说似乎不是正确的解决方案。

【问题讨论】:

    标签: django python-3.x twitter tweepy


    【解决方案1】:

    我不知道您获得或想要存储的所有字段,但是对于我在您的代码中看到的内容,这应该可以工作(将 max_length 设置为它应该执行的操作,我不知道):

    Tweet(models.Model):
        author = models.Charfield(max_length=50)
        text = models.Charfield(max_length=500)
        author_profile_url = models.URLField(null=True, blank=True)
        reply_to = models.ForeignKey(Tweet, on_delete=models.CASCADE, related_name='replies')
        creation_date = models.DateTimeField()
    

    要打印所有对话,您需要迭代 FK 以查找所有相关对象并按 creation_date 对它们进行排序。

    如果您只想显示一个对话,您应该通过视图发送对话的初始对象,然后您可以执行以下操作:

    {{ tweet.author }}
    {{ tweet.text }}
    {{ tweet.creation_date }}
    {% if tweet.reply_to_set.count > 0 %}
        {% with replies=tweet.reply_to_set.all %}
            {% for reply in replies %}
                {{ reply.author }}
                {{ reply.text }}
                {{ reply.creation_date }}
                replies to this message: {{ reply.reply_to_set.count }}
            {% endfor %}
        {% endwith %}
    {% endif %}
    

    这将首先显示推文信息,然后检查是否有回复,如果有则显示每个人的信息。在该回复中,我添加了replies to this message,您可以在其中让人们知道该回复是否有其他回复。以防万一你想做无限回复系统(比如推特)。但是你可以在其中添加一个链接到这个相同的模板,其中对象是那个回复,所以这将是主要的推文,然后回复就会显示出来。

    【讨论】:

    • 但是如何将它们发送到模板并呈现为对话?
    • 我是否需要某种 Thread 类来组合这些消息?这是我目前看到的唯一解决方案。
    • @BogdanKozlovskyi 我用这些信息编辑了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2018-06-21
    • 2013-03-31
    • 2020-04-16
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多