2,556   Django Python

上文说到已经成功链接MySQL了,并且新建了Django的默认功能表格,本文讲讲新建一些自定义的表格

 

1,首先编写models文件,用来生成表格的SQL以及操作表格的方法,进入之前创建的Web项目目录polls,修改polls/models.py

from django.db import models

# 类名就是表格名称
class Question(models.Model):
    # 变量名就是字段名,CharField表示字段是char类型
    question_text = models.CharField(max_length=200)
    # DateTimeField就是datetime类型
    pub_date = models.DateTimeField('date published')
    # 对象默认返回内容
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    # 通过外键把Choice关联到Question
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

 

2,把polls项目的配置添加到mysite/settings.py,以便初始化时polls包括激活models

INSTALLED_APPS = [
    # polls
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

 

3,初始化polls项目的models,即生成表格的sql,到时会生成文件polls/migrations/0001_initial.py,可通过命令查看具体sql

$ python manage.py makemigrations polls

Migrations for 'polls':
  polls/migrations/0001_initial.py:
    - Create model Choice
    - Create model Question
    - Add field question to choice


$ python manage.py sqlmigrate polls 0001

BEGIN;
--
-- Create model Choice
--
CREATE TABLE `polls_choice` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `choice_text` varchar(200) NOT NULL, `votes` integer NOT NULL);
--
-- Create model Question
--
CREATE TABLE `polls_question` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `question_text` varchar(200) NOT NULL, `pub_date` datetime NOT NULL);
--
-- Add field question to choice
--
ALTER TABLE `polls_choice` ADD COLUMN `question_id` integer NOT NULL;
ALTER TABLE `polls_choice` ALTER COLUMN `question_id` DROP DEFAULT;
CREATE INDEX `polls_choice_7aa0f6ee` ON `polls_choice` (`question_id`);
ALTER TABLE `polls_choice` ADD CONSTRAINT `polls_choice_question_id_c5b4b260_fk_polls_question_id` FOREIGN KEY (`question_id`) REFERENCES `polls_question` (`id`);
COMMIT;

 

 

4,接着就是执行sql啦,生成自定义的表格,通过mysql命令查看下新健的自定义表格

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Rendering model states... DONE
  Applying polls.0001_initial... OK


mysql> show create table polls_choice;
+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table        | Create Table                                                                                                                                                                                                                                                                                         |
+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| polls_choice | CREATE TABLE `polls_choice` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `choice_text` varchar(200) NOT NULL,
  `votes` int(11) NOT NULL,
  `question_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `polls_choice_7aa0f6ee` (`question_id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 |
+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

 

5,表格有了,那就试下操作表格添加数据,Django的models类已经集成了丰富数据库操作函数,进入python的命令行测试下

 

$ python manage.py shell
>>> from polls.models import Question, Choice 
>>> from django.utils import timezone 
>>> q = Question(question_text="What's new?",pub_date=timezone.now()) 
>>> q.save() 
>>> q.id 
1L 
>>> q.question_text 
"What's new?" 
>>> q.question_text="What's up?" 
>>> q.save() 
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
>>> q = Question.objects.get(id=1) 
>>> q.question_text u"What's up?" 
>>> q.choice_set.create(choice_text='Not much',votes=0) 
>>> q.choice_set.create(choice_text='The sky',votes=0) 
>>> c = q.choice_set.create(choice_text='Just hacking again',votes=0) 
>>> c.question 
>>> q.choice_set.all() 
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]> 
>>> q.choice_set.count() 
3

Django更多的数据库操作方法参考这里

 

 

6,上一篇文章说到了Django的后台,只有默认的admin表格管理,现在把自定义的表格也加进去

$ vim polls/admin.py
from django.contrib import admin

from .models import Question

admin.site.register(Question)

 

 

7,重启Django,进入后台页面 http://127.0.0.1:8000/admin/ 登录

$ python manage.py runserver



Leave a Reply

Your email address will not be published. Required fields are marked *