Django(二)-搭建第一个应用(1)

一、项目环境和结构

1、项目环境

2、项目结构

二、编写项目

1、创建模型

++代码示例:++

python 复制代码
import datetime

from django.db import models
from django.utils import timezone


# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    # 如果不自定义字段名,默认就是变量名:比如此例的pub_date
    pub_date = models.DateTimeField("data published")

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    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、激活模型

3、生成迁移文件

主要用于生成模型对应的数据库表结构,注意此时还没有执行迁移,该文件只是描述应该执行哪些sql操作。

++将会看到如下输出:++

++并且在migrations文件夹中生成如下文件:sql操作命令++

++通过以下语句可查 看迁移命令会执行哪些 SQL 语句:++

python 复制代码
$ python manage.py sqlmigrate polls 0001

​编辑4、执行迁移

migrate 命令选中所有还没有执行过的迁移(Django 通过在数据库中创建一个特殊的表 django_migrations 来跟踪执行过哪些迁移)并应用在数据库上 - 也就是将你对模型的更改同步到数据库结构上。

bash 复制代码
$ python manage.py migrate

5、创建管理员账号

bash 复制代码
$ python manage.py createsuperuser
Username: admin
Email address: maplea2012@gmail.com
Password: **********
Password (again): *********
Superuser created successfully.

6、访问管理员后台

7、向管理员页面中加入投票应用

++添加完成之后的页面:++

点击Questions:

++点击 "What's up?" 可编辑这个问题(Question)对象++:

相关推荐
Zoey的笔记本21 小时前
敏捷与稳定并行:Scrum看板+BPM工具选型指南
大数据·前端·数据库·python·低代码
开开心心就好1 天前
图片格式转换工具,右键菜单一键转换简化
linux·运维·服务器·python·django·pdf·1024程序员节
骥龙1 天前
1.2下、工欲善其事:物联网安全研究环境搭建指南
python·物联网·安全
Lxinccode1 天前
BUG(20) : response.text耗时很久, linux耗时十几秒, Windows耗时零点几秒
python·bug·requests·response.text·response.text慢
智航GIS1 天前
11.2 Matplotlib 数据可视化教程
python·信息可视化·matplotlib
技术净胜1 天前
Python 操作 Cookie 完全指南,爬虫与 Web 开发实战
前端·爬虫·python
海棠AI实验室1 天前
第六章 日志体系:logging 让排错效率翻倍
python·logging
laufing1 天前
flask_restx 创建restful api
python·flask·restful
毕设源码-郭学长1 天前
【开题答辩全过程】以 基于python电商商城系统为例,包含答辩的问题和答案
开发语言·python