Django -- Rango - Models & manage.py 自定义命令

Models 定义

  • Category
  • Page
# rango/models.py
from django.db import models

class Category(models.Model):
    title = models.CharField(max_length=64, unique=True)
    pinyin = models.CharField(max_length=128, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    url = models.URLField(max_length=200)
    like = models.IntegerField(default=0)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.title

class Page(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
    url = models.URLField(max_length=200)
    view = models.IntegerField(default=0)

    def __str__(self):
        return self.name

以下代码修复了 Django Admin 中标题复数显示的问题,默认是直接在后面加 s

    class Meta:
        verbose_name_plural = 'Categories'
verbose_name_plural

自定义 manage.py 命令

以下代码通过自定义 manage.py 命令来插入数据,数据通过爬虫在豆瓣电影获取

  • 新建包(Python Package)目录:rango/management/commands
目录结构
from django.core.management import BaseCommand, CommandError
from rango.models import Category, Page

class Command(BaseCommand):
help = 'execute this command to build data on database'

#def add_arguments(self, parser):
#    parser.add_augument()

def handle(self, *args, **options):
    filename = 'doubanMovies.txt'
    with open(filename, encoding='utf-8') as file:
        current_category = None
        for line in file:
            line = line.strip()
            if line.endswith(':'):
                line = line[:-1]
                line = line.split()
                title = line[0]
                pinyin = line[1]
                url = '/rango/category/'+ pinyin
                current_category = Category.objects.create(title=title, pinyin=pinyin, url=url)
                self.stdout.write('Create Category: ' + title + ' -- ' + url)
            else:
                content = line.split()
                current_category.page_set.create(name=content[0], url=content[1])
                self.stdout.write('  Create Page: ' + content[0] + ' -- ' + content[1])

爬虫代码:Github -- doubanMovies

执行自定义命令

注意!因为 python manage.py buildData 是在包含 mange.py 文件的目录执行的,所以爬虫结果的文件 doubanMovies.txt 要放在和 manage.py 同级的目录


数据已添加

你可能感兴趣的:(Django -- Rango - Models & manage.py 自定义命令)