Django 一对多关系

1,创建 Django 应用

Test/app9

django-admin startapp app9

2,注册应用

Test/Test/settings.py

3,添加应用路由

Test/Test/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app9.urls')),
    path('app1/', include('app1.urls')),
    path('app2/', include('app2.urls')),
    path('app3/', include('app3.urls')),
    path('app4/', include('app4.urls')),
    path('app5/', include('app5.urls')),
    path('app6/', include('app6.urls')),
    path('app7/', include('app7.urls')),
    path('app8/', include('app8.urls')),
    path('app9/', include('app9.urls')),
]

4,添加模型

Test/app9/models.py

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')

    def __str__(self):
        return self.title

5,注册模型到admin

Test/app9/admin.py

from django.contrib import admin
from .models import Author, Book

admin.site.register(Author)
admin.site.register(Book)

5.1 创建超级账号

python manage.py createsuperuser

按照提示输入用户名、邮箱和密码。

5.2 通过admin管理后台添加数据

http://127.0.0.1:8000/admin/
http://127.0.0.1:8000/admin/login/?next=/admin/

添加作者

  • 点击 "Authors"。
  • 点击右上角的 "Add Author"。
  • 输入作者名称,例如 "小强"。
  • 点击 "Save"。

添加书籍

  • 点击 "Books"。
  • 点击右上角的 "Add Book"。
  • 输入书名,例如 "java入门到弃坑233"。
  • 在 "Author" 字段选择刚才添加的作者 "小强"。
  • 点击 "Save"。
  • 重复以上步骤添加更多书籍,例如 "学习msql"。

查看数据库:

app9_author表,id 为2的作者小强,关联app9_book表author_id为2的两本书籍,建立了一对多的关系

5.3 执行py脚本实例化添加数据

Test/populate_data.py

import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Test.settings')
django.setup()

from app9.models import Author, Book

# 清空现有数据
Author.objects.all().delete()
Book.objects.all().delete()

# 添加作者和书籍
author1 = Author.objects.create(name="小强")
Book.objects.create(title="Django 从入门到入坑", author=author1)
Book.objects.create(title="pyhton 从入门到入坑", author=author1)

author2 = Author.objects.create(name="小龙")
Book.objects.create(title="C++ 从入门到入坑", author=author2)
Book.objects.create(title="java 从入门到入坑", author=author2)

print("数据添加成功!")

查看管理台:

查看数据库:

6,添加视图函数

Test/app9/views.py

from django.shortcuts import render, get_object_or_404
from .models import Author, Book

def author_list(request):
    authors = Author.objects.all()
    return render(request, '9/author_list.html', {'authors': authors})

def author_detail(request, author_id):
    author = get_object_or_404(Author, pk=author_id)
    return render(request, '9/author_detail.html', {'author': author})

7,添加html代码

Test/templates/9/author_list.html

<!DOCTYPE html>
<html>
<head>
    <title>Authors</title>
</head>
<body>
    <h1>Authors</h1>
    <ul>
        {% for author in authors %}
            <li><a href="{% url 'author_detail' author.id %}">{{ author.name }}</a></li>
        {% endfor %}
    </ul>
</body>
</html>

Test/templates/9/author_detail.html

<!DOCTYPE html>
<html>
<head>
    <title>{{ author.name }}</title>
</head>
<body>
    <h1>{{ author.name }}</h1>
    <h2>Books</h2>
    <ul>
        {% for book in author.books.all %}
            <li>{{ book.title }}</li>
        {% endfor %}
    </ul>
    <a href="{% url 'author_list' %}">Back to Authors</a>
</body>
</html>

8,添加路由地址

Test/app9/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('authors/', views.author_list, name='author_list'),
    path('authors/<int:author_id>/', views.author_detail, name='author_detail'),
]

9,访问页面

http://127.0.0.1:8000/app9/authors/

点击作者小强,可以看到他名下的书籍

10,删除作者和书籍

10.1 添加删除视图函数

Test/app9/views.py

from django.shortcuts import render, get_object_or_404
from .models import Author, Book

def author_list(request):
    authors = Author.objects.all()
    return render(request, '9/author_list.html', {'authors': authors})

def author_detail(request, author_id):
    author = get_object_or_404(Author, pk=author_id)
    return render(request, '9/author_detail.html', {'author': author})


# 删除书籍
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages

from .models import Author, Book

def delete_author(request, author_id):
    author = get_object_or_404(Author, pk=author_id)

    if request.method == 'POST':
        author.delete()
        messages.success(request, '作者已成功删除!')
        return redirect('author_list')  # 重定向到作者列表视图

    return render(request, '9/confirm_delete_author.html', {'author': author})

10.2 添加删除html模版

Test/templates/9/confirm_delete_author.html

<h1>确认删除作者</h1>
<p>你确定要删除 "{{ author.name }}" 吗?</p>
<form method="POST">
    {% csrf_token %}
    <button type="submit">确认删除</button>
    <a href="{% url 'author_list' %}">取消</a>
</form>

10.3 给列表html添加删除按钮

Test/templates/9/author_list.html

<!DOCTYPE html>
<html>
<head>
    <title>Authors</title>
</head>
<body>
    <h1>Authors</h1>
    <ul>
        {% for author in authors %}
            <li><a href="{% url 'author_detail' author.id %}">{{ author.name }}</a></li>
        {% endfor %}
    </ul>



    <ul>
        {% for author in authors %}
            <li>
                {{ author.name }}
                <a href="{% url 'delete_author' author.id %}">删除</a>
            </li>
        {% endfor %}
    </ul>



</body>
</html>

10.4 添加路由地址

Test/app9/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('authors/', views.author_list, name='author_list'),
    path('authors/<int:author_id>/', views.author_detail, name='author_detail'),

    path('delete_author/<int:author_id>/', views.delete_author, name='delete_author'),
]

10.5 访问页面

http://127.0.0.1:8000/app9/authors/

对比数据库删除前后,可以看到与小强关联的两本书,在删除作者小强后也被一并删除了。

相关推荐
秀儿还能再秀25 分钟前
机器学习——简单线性回归、逻辑回归
笔记·python·学习·机器学习
阿_旭1 小时前
如何使用OpenCV和Python进行相机校准
python·opencv·相机校准·畸变校准
幸运的星竹1 小时前
使用pytest+openpyxl做接口自动化遇到的问题
python·自动化·pytest
杨哥带你写代码2 小时前
网上商城系统:Spring Boot框架的实现
java·spring boot·后端
camellias_2 小时前
SpringBoot(二十一)SpringBoot自定义CURL请求类
java·spring boot·后端
背水2 小时前
初识Spring
java·后端·spring
晴天飛 雪2 小时前
Spring Boot MySQL 分库分表
spring boot·后端·mysql
weixin_537590452 小时前
《Spring boot从入门到实战》第七章习题答案
数据库·spring boot·后端