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)对象++:

相关推荐
xiaoqi019531 分钟前
机器学习因子分析实战:从量化特征到可视化决策
人工智能·python·机器学习
Escalating_xu42 分钟前
【Python】基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
happylifetree1 小时前
Python14:核心语法-数据存储与运算-字符串定义
python
hhb_6181 小时前
AIRAGDebug:一键定位RAG链路异常
人工智能·python·算法
小静AI工程实验室2 小时前
asyncio.Queue 有界队列实战:背压、task_done、join 与异常收尾
python
小凡geo2 小时前
本地商家 GEO:用脚本一键生成 FAQPage 结构化数据,让 AI 切片更稳
开发语言·人工智能·python·microsoft·搜索引擎·ai
Zhou1411362 小时前
SpringBoot_03_Web开发
前端·spring boot·python
weixin199701080162 小时前
《1688物流API接口边界:logistics.trace.get 与 freight.template.list 的隐藏约束》(附Python源码)
windows·python·list
mhmh1232 小时前
Python 对象模型与数据模型:魔术方法、描述符与元类深度解析
开发语言·python
估值探索者3 小时前
【Python量化策略实战 #02】多因子合成mom和vol两因子打分合成
开发语言·c++·python·数据挖掘·c#