如何在Scrapy中更新DjangoItem

时间:2014-05-14 19:27:08

标签: python django scrapy

我一直在使用Scrapy,但遇到了一些问题。

DjangoItem有一个save方法来使用Django ORM来持久保存项目。这很好,除非我多次运行一个刮刀,即使我可能只想更新以前的值,也会在数据库中创建新项目。

查看文档和源代码后,我看不到任何更新现有项目的方法。

我知道我可以调用ORM来查看项目是否存在并更新它,但这意味着要为每个对象调用数据库,然后再次保存项目。

如果项目已经存在,我该如何更新?

3 个答案:

答案 0 :(得分:10)

不幸的是,我发现完成此操作的最佳方法是完全按照所述内容执行操作:使用django_model.objects.get检查数据库中是否存在该项,然后更新它。

在我的设置文件中,我添加了新的管道:

ITEM_PIPELINES = {
    # ...
    # Last pipeline, because further changes won't be saved.
    'apps.scrapy.pipelines.ItemPersistencePipeline': 999
}

我创建了一些辅助方法来处理创建项目模型的工作,并在必要时创建一个新方法:

def item_to_model(item):
    model_class = getattr(item, 'django_model')
    if not model_class:
        raise TypeError("Item is not a `DjangoItem` or is misconfigured")

    return item.instance


def get_or_create(model):
    model_class = type(model)
    created = False

    # Normally, we would use `get_or_create`. However, `get_or_create` would
    # match all properties of an object (i.e. create a new object
    # anytime it changed) rather than update an existing object.
    #
    # Instead, we do the two steps separately
    try:
        # We have no unique identifier at the moment; use the name for now.
        obj = model_class.objects.get(name=model.name)
    except model_class.DoesNotExist:
        created = True
        obj = model  # DjangoItem created a model for us.

    return (obj, created)


def update_model(destination, source, commit=True):
    pk = destination.pk

    source_dict = model_to_dict(source)
    for (key, value) in source_dict.items():
        setattr(destination, key, value)

    setattr(destination, 'pk', pk)

    if commit:
        destination.save()

    return destination

然后,最后的管道非常简单:

class ItemPersistencePipeline(object):
    def process_item(self, item, spider):
        try:
             item_model = item_to_model(item)
        except TypeError:
            return item

        model, created = get_or_create(item_model)

        update_model(model, item_model)

        return item

答案 1 :(得分:1)

与外国钥匙相关的模型

def update_model(destination, source, commit=True):
    pk = destination.pk

    source_fields = fields_for_model(source)
    for key in source_fields.keys():
        setattr(destination, key, getattr(source, key))

    setattr(destination, 'pk', pk)

    if commit:
        destination.save()

    return destination

答案 2 :(得分:1)

我认为可以更简单地完成

class DjangoSavePipeline(object):
    def process_item(self, item, spider):
        try:
            product = Product.objects.get(myunique_id=item['myunique_id'])
            # Already exists, just update it
            instance = item.save(commit=False)
            instance.pk = product.pk
        except Product.DoesNotExist:
            pass
        item.save()
        return item

假设您的django模型从抓取的数据中获得了一些唯一的ID,例如产品ID,这里假设您的Django模型称为Product