Python 从0开始 一步步基于Django创建项目(2)创建应用程序&数据模型

本文内容建立在《Python 从0开始 一步步基于Django创建项目(1)》的基础上。

Django项目由一系列应用程序组成。

本文将创建一个‘应用程序’,其中包含两个‘数据类’(数据模型),每个‘数据类’有若干不同类型的数据成员。

将‘应用程序’包含到Django项目中,以使用这些‘数据模型’。

在数据库中,为‘数据模型’生成对应表格,存储相关数据。

以下逐步完成。

1、创建应用程序

1)将路径切换到虚拟环境的Scripts文件夹,运行其中的activate,激活虚拟环境

C:\D\Python\Python310\study\snap_gram>cd C:\D\Python\Python310\study\snap_gram\sg_env\Scripts

C:\D\Python\Python310\study\snap_gram\sg_env\Scripts>activate

(sg_env) C:\D\Python\Python310\study\snap_gram\sg_env\Scripts>

以上为Windows系统的激活方法。

2)切换回根目录

(sg_env) C:\D\Python\Python310\study\snap_gram>

3)执行命令,创建项目city_infos,在manage.py文件所在的根目录,生成名为city_infos的文件夹。数据模型就定义在该文件夹的models.py文件中。

(sg_env) C:\D\Python\Python310\study\snap_gram>python manage.py startapp city_infos

2、编写应用程序的数据类。

1)打开文件models.py,其路径是:C:\D\Python\Python310\study\snap_gram\city_infos

2)编写数据类,这里编写了两个数据类,城市类,城市信息类。

from django.db import models

# Create your models here.

class City(models.Model):
    '''city name'''
    name = models.CharField(max_length=100)
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'cities'#正确显示city的复数形式

    def __str__(self):
        '''return city name'''
        return self.name


class Entry(models.Model):
    '''information of city'''

    #将info关联的city,一个city可以关联多个info,当删除city时级联删除info
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    info = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        '''return city info'''
        return f"{self.info[:50]}..."

3、激活数据模型

1)打开文件settings.py,其路径是:C:\D\Python\Python310\study\snap_gram\snap_gram

2)修改文件内容如下

# Application definition

INSTALLED_APPS = [
    #my app
    'city_infos',
    #auto app
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

4、为数据模型修改数据库

1)在控制台输入命令python manage.py makemigrations city_infos,生成数据库更新文件0001_initial,其路径是:C:\D\Python\Python310\study\snap_gram\city_infos\migrations

(sg_env) C:\D\Python\Python310\study\snap_gram>python manage.py makemigrations city_infos
Migrations for 'city_infos':
  city_infos\migrations\0001_initial.py
    - Create model City
    - Create model Entry

(sg_env) C:\D\Python\Python310\study\snap_gram>

2)在控制台输入命令python manage.py migrate,使用更新文件0001_initial更新数据库

(sg_env) C:\D\Python\Python310\study\snap_gram>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, city_infos, contenttypes, sessions
Running migrations:
  Applying city_infos.0001_initial... OK

(sg_env) C:\D\Python\Python310\study\snap_gram>

注意:以后每次对‘数据模型’进行修改,都需要重复本部分操作,即生成数据库更新文件,使用更新文件更新数据库。

  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 创建Django项目 在命令行运行以下命令: ``` django-admin startproject project_name ``` 2. 创建应用程序 在命令行进入项目文件夹并运行以下命令: ``` python manage.py startapp app_name ``` 3. 配置数据库 打开项目文件夹的settings.py文件,在DATABASES配置数据库连接信息。 ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_name', 'USER': 'database_user', 'PASSWORD': 'database_password', 'HOST': 'localhost', 'PORT': '3306', } } ``` 4. 创建模型 在应用程序文件夹的models.py文件定义模型类,如: ``` from django.db import models class User(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=254) password = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'user' ``` 5. 创建视图 在应用程序文件夹的views.py文件定义视图函数,如: ``` from django.shortcuts import render from .models import User def user_list(request): users = User.objects.all() context = {'users': users} return render(request, 'user_list.html', context) ``` 6. 创建模板 在应用程序文件夹创建templates文件夹,然后在其创建HTML模板文件,如: ``` <!DOCTYPE html> <html> <head> <title>User List</title> </head> <body> <h1>User List</h1> <ul> {% for user in users %} <li>{{ user.name }} - {{ user.email }}</li> {% endfor %} </ul> </body> </html> ``` 7. 配置URL 在应用程序文件夹的urls.py文件定义URL路由,如: ``` from django.urls import path from .views import user_list urlpatterns = [ path('users/', user_list, name='user_list'), ] ``` 8. 运行Django项目 在命令行运行以下命令: ``` python manage.py runserver ``` 现在您可以在浏览器访问http://localhost:8000/users/,查看用户列表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值