【问题标题】:Foreign Keys on ScrapyScrapy 上的外键
【发布时间】:2013-02-22 05:14:46
【问题描述】:

我正在用 scrapy 做一个废品,我在 django 上的模型是:

class Creative(models.Model):
    name = models.CharField(max_length=200)
    picture = models.CharField(max_length=200, null = True)

class Project(models.Model):
    title = models.CharField(max_length=200)
    description = models.CharField(max_length=500, null = True)
    creative = models.ForeignKey(Creative)

class Image(models.Model):
    url = models.CharField(max_length=500)
    project = models.ForeignKey(Project)

还有我的scrapy模型:

from scrapy.contrib.djangoitem import DjangoItem
from app.models import Project, Creative

class ProjectItems(DjangoItem):
    django_model = Project

class CreativeItems(DjangoItem):
    django_model = Creative

所以当我保存时:

creative["name"]  = hxs.select('//*[@id="owner"]/text()').extract()[0]
picture  = hxs.select('//*[@id="owner-icon"]/a/img/@src').extract()
if len(picture)>0:
    creative["picture"] = picture[0]
creative.save()


# Extract title and description of the project
project["title"] = hxs.select('//*[@id="project-title"]/text()').extract()[0]
description = hxs.select('//*[@class="project-description"]/text()').extract()
if len(description)>0:
    project["description"] = description[0]
project["creative"] = creative
project.save()

我得到了错误:

Project.creative”必须是“Creative”实例。

那么,我怎样才能在scrapy上添加一个外键值呢?

【问题讨论】:

  • creative是通过实例化Creative创建的吗?
  • 能否包含错误的整个回溯?

标签: django django-models web-scraping scrapy scrape


【解决方案1】:

这可以通过将creative.save() 的返回值分配给project['creative'] 的值来完成。例如,在以下示例中,我们使用djangoCreativeItem 变量将此信息传递给项目:

creative["name"]  = hxs.select('//*[@id="owner"]/text()').extract()[0]
picture  = hxs.select('//*[@id="owner-icon"]/a/img/@src').extract()   
if len(picture)>0:
    creative["picture"] = picture[0]
djangoCreativeItem = creative.save()

# Extract title and description of the project
project["title"] = hxs.select('//*[@id="project-title"]/text()').extract()[0]
description = hxs.select('//*[@class="project-description"]/text()').extract()
if len(description)>0:
    project["description"] = description[0]
project["creative"] = djangoCreativeItem
project.save()

【讨论】:

    【解决方案2】:

    it's been done here一样,把你的广告的ID直接放在creative_id里,我想应该可以的:

     project["creative_id"] = creative.id
    

    它将指定外键,而不会因为缺少对象而打扰您(因为您处于不直接接触模型对象的 Scrapy 环境中......)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多