安装完 Django 后我们要对抓取的数据建 model 以便可以让 django 的 orm 来使用


首先,要创建一个 app

cd /path/to/workspace/dugong/
python manage.py startapp books

接着,给 books app 添加 models

from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _


class Book(models.Model):
title = models.CharField(_('title'), max_length=255, blank=False, null=False)
desc = models.TextField(null=True, blank=True)
price = models.DecimalField(max_digits=10,
decimal_places=2,
default=0)
asin = models.SlugField(max_length=255, unique=True, null=False)
origin_link = models.URLField(max_length=255, default='')
create_datetime = models.DateTimeField(default=timezone.now,
editable=False,
db_index=True)
status = models.BooleanField(_('status'), default=False)

@property
def image_urls(self):
try:
return [row.image.url for row in self.images.all()]
except Exception as e:
return []

def __unicode__(self):
return self.title

def get_purchase_link(self): #生成亚马逊购买链接
return "{url}?tag=xxxxxx".format(url=self.origin_link)

def get_first_image_url(self):
if len(self.image_urls) > 0:
return self.image_urls[0]


class Image(models.Model):
book = models.ForeignKey(Book, related_name='images')
image = models.ImageField(upload_to='book/images/')
create_datetime = models.DateTimeField(default=timezone.now,
editable=False,
db_index=True)
def __unicode__(self):
return self.image.url


解释下以上代码:

Book model 主要包含字段:

title 书名

desc 书的描述

price 价格

asin 亚马逊商品唯一 ID

origin_link 原始链接


Image model 包含字段:

book 为 Book model 的外键

image 图片

create_datetime 创建时间


最后,创建数据库执行以下命令

python manage.py makemigrations books
python manage.py migrate