带外键的废Djangoitem

2024-10-02 16:30:33 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题被问到这里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中,这是可行的:

^{pr2}$

恶心的东西:

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

我们到底该怎么办?在


Tags: djangoidtrue管道定义objectmodelsdef
1条回答
网友
1楼 · 发布于 2024-10-02 16:30:33

好吧,我设法解决了这个问题,我要在这里备案。正如最后一个exceptions.TypeError所暗示的,item['category'] expects an instance ofcategoryclass, in my case I am using [django categories][1] so in the pipeline just replace with this (assumecategory`已经填充到ORM中):

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

相关问题 更多 >