Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从Django数据库中删除重复对象的最佳方法是什么_Python_Django_Postgresql_Celery - Fatal编程技术网

Python 从Django数据库中删除重复对象的最佳方法是什么

Python 从Django数据库中删除重复对象的最佳方法是什么,python,django,postgresql,celery,Python,Django,Postgresql,Celery,我正在挖掘Twitter搜索API以查找某个hashtag的tweet,并使用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_K

我正在挖掘Twitter搜索API以查找某个hashtag的tweet,并使用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()

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

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

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

当你说
duplicate
时,你指的是哪个字段?
tweet\u id
需要是唯一的,我在模型中将其设置为唯一的,但是当芹菜尝试创建新对象并将其保存到数据库时,它会挂起,并出现一个关键错误。这似乎就是我要寻找的。我的第一个想法是例外,但我不知道什么例外。谢谢