1

私はスクレイピーでスクラップをしており、ジャンゴの私のモデルは次のとおりです。

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)

そして私のスクレイピーモデル:

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」インスタンスでなければなりません。

では、どうすればスクレイピーにフォアキー値を追加できますか?

4

2 に答える 2

2

これは、の戻り値をcreative.save()at の値に代入することで実行でき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()
于 2013-10-23T19:00:09.320 に答える
1

ここで行われたように、クリエイティブの ID を直接creative_id に入れてください。うまくいくはずです:

 project["creative_id"] = creative.id

オブジェクトの欠落に悩まされることなく、外部キーを指定します (モデルオブジェクトに直接触れない Scrapy 環境にいるため...)。

于 2013-08-05T11:42:21.797 に答える