【问题标题】:What is the best way to remove duplicate objects from the Django database从 Django 数据库中删除重复对象的最佳方法是什么
【发布时间】:2016-10-24 11:00:23
【问题描述】:

我正在 Twitter 搜索 API 中挖掘某个主题标签的推文,并使用 Django ORM 将它们存储到 Postgresql 数据库中。

这是我的tasks.py 文件中处理此例程的代码。

"""Get some tweets and store them to the database using Djano's ORM."""

import tweepy
from celery import shared_task

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = tweepy.API(auth, wait_on_rate_limit=True)


@shared_task(name='get_tweets')
"""Get some tweets from the twiter api and store them to the db."""
def get_tweets():
    tweets = api.search(
        q='#python',
        since='2016-06-14',
        until='2016-06-21',
        count=5
    )
    tweets_date = [tweet.created_at for tweet in tweets]
    tweets_id = [tweet.id for tweet in tweets]
    tweets_text = [tweet.text for tweet in tweets]

    for i, j, k in zip(tweets_date, tweets_id, tweets_text):
        update = Tweet(
            tweet_date=i,
            tweet_id=j,
            tweet_text=k
        )
        update.save()

这是我的models.py

from django.db import models


class Tweet(models.Model):
    tweet_date = models.DateTimeField()
    tweet_id = models.CharField(max_length=50, unique=True)
    tweet_text = models.TextField()

    def __str__(self):
        return str(self.tweet_date) + '  |  ' + str(self.tweet_id)

我得到了重复,对 Twitter API 做。

有没有办法在对象保存到数据库之前检查重复项。这里:

for i, j, k in zip(tweets_date, tweets_id, tweets_text):
        update = Tweet(
            tweet_date=i,
            tweet_id=j,
            tweet_text=k
        )
        update.save()

这是我可以在此处的提取过程中处理的事情,还是我需要在之后清理的事情,例如在转换阶段?

【问题讨论】:

  • 当您说duplicate 时,您指的是哪个字段?
  • tweet_id 需要是唯一的,我在模型中设置为唯一,但是当 Celery 尝试创建新对象并将它们保存到数据库时,它会挂起一个关键错误。跨度>

标签: python django postgresql celery


【解决方案1】:

您可以让您的模型经理为您完成这项工作

from django.db import IntegrityError

for i, j, k in zip(tweets_date, tweets_id, tweets_text):
    try:
        Tweet.objects.create(
            tweet_date=i,
            tweet_id=j,
            tweet_text=k
        )
    except IntegrityError:
        log('duplicate tweet id {}'.format(j) 
        pass

【讨论】:

  • 这似乎就是我想要的。我的第一个想法是例外,但我不知道是什么例外。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 2019-09-01
  • 1970-01-01
相关资源
最近更新 更多