【问题标题】:scrapy djangoitem with Foreign Key带有外键的scrapy djangoitem
【发布时间】:2014-06-21 06:38:13
【问题描述】:

这个问题是在这里Foreign Keys on Scrapy 提出的,但没有得到接受的答案,所以我在这里用更明确的最低设置重新提出这个问题:

django 模型:

class Article(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    category = models.ForeignKey('categories.Category', null=True, blank=True)

注意category 的定义在这里无关紧要,但它确实使用了ForeignKey。所以,在 django shell 中,这会起作用:

c = Article(title="foo", content="bar", category_id=2)
c.save()

scrapy 项目:

class BotsItem(DjangoItem):
    django_model = Article

scrapy 管道:

class BotsPipeline(object):
    def process_item(self, item, spider):
        item['category_id'] = 2
        item.save()
        return item

使用上面的代码,scrapy 报错:

exceptions.KeyError: 'BotsItem does not support field: category_id'

公平,因为category_id 没有出现在 django 模型中,我们从中得到了 scrapy 项目。作为记录,如果我们有管道(假设我们有一个类别foo):

class BotsPipeline(object):
    def process_item(self, item, spider):
        item['category'] = 'foo'
        item.save()
        return item

现在scrapy抱怨:

exceptions.TypeError: isinstance() arg 2 must be a class, type, or tuple
 of classes and types

那么我们到底应该怎么做呢?

【问题讨论】:

    标签: python django scrapy


    【解决方案1】:

    好的,我设法解决了这个问题,我在这里记录一下。正如最后一个exceptions.TypeError 所暗示的那样,item['category'] 需要一个Category 类的实例,在我的情况下,我使用的是django-categories,所以在管道中只需替换为这个(假设Category 已经填充在ORM 中):

    class BotsPipeline(object):
        def process_item(self, item, spider):
            item['category'] = Category.objects.get(id=2)
            item.save()
            return item
    

    【讨论】:

    • 至少,你可以试试;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多