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

相关推荐
算法_小学生19 分钟前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode
230万光年的思念41 分钟前
【无标题】
python
shengli7221 小时前
机器学习与人工智能
jvm·数据库·python
2301_765703141 小时前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python
追风少年ii1 小时前
多组学扩展---分子对接pyrosetta
python·数据分析·空间·单细胞
2301_821369612 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
m0_561359672 小时前
使用Kivy开发跨平台的移动应用
jvm·数据库·python
编程火箭车2 小时前
04.第一个 Python 程序:Hello World 从编写到运行全解析
python·python第一个程序·python入门报错解决·python新手教程·hello world 程序·python终端运行·pycharm运行代码
qq_423233902 小时前
如何用FastAPI构建高性能的现代API
jvm·数据库·python
疯狂踩坑人3 小时前
【Python版 2026 从零学Langchain 1.x】(二)结构化输出和工具调用
后端·python·langchain