这个问题被问到这里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中,这是可行的:
恶心的东西:
class BotsItem(DjangoItem):
django_model = Article
废管道:
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模型中,我们从中得到了残羹剩饭。作为记录,如果我们有管道(假设我们有一个类别foo
):
class BotsPipeline(object):
def process_item(self, item, spider):
item['category'] = 'foo'
item.save()
return item
现在,斯皮奇抱怨:
exceptions.TypeError: isinstance() arg 2 must be a class, type, or tuple
of classes and types
我们到底该怎么办?在
好吧,我设法解决了这个问题,我要在这里备案。正如最后一个
exceptions.TypeError
所暗示的,item['category'] expects an instance of
categoryclass, in my case I am using [
django categories][1] so in the pipeline just replace with this (assume
category`已经填充到ORM中):相关问题 更多 >
编程相关推荐