ORM多表操作练习

 

 

 

 orm_lx2.settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',  # app01应用注册
]


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '20211202',
        'USER': 'root',
        'PASSWORD': '123456',
        'PORT': 3306,
        'HOST': '127.0.0.1',
    }
}


STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "statics"),
]

orm_lx2.__init__.py

import pymysql

pymysql.install_as_MySQLdb()

orm_lx2.urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", views.check),
    path("app01/", include("app01.urls")),
]

app01.models.py

from django.db import models

# Create your models here.


class Publish(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()


class Authordetails(models.Model):
    id = models.AutoField(primary_key=True)
    birthday = models.DateField()
    telephone = models.BigIntegerField()
    addr = models.TextField()


class Author(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    gender = models.CharField(max_length=32, default="")
    authordetail = models.OneToOneField(to="Authordetails", to_field="id", on_delete=models.CASCADE)


class Book(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    pub_date = models.DateField()
    publish = models.ForeignKey(to="Publish", to_field="id", on_delete=models.CASCADE)
    authors = models.ManyToManyField(to="Author")

app01.urls.py

from django.urls import path
from app01 import views


urlpatterns = [
    path("add_publish/", views.add_publish),
    path("add_authordetails/", views.add_authordetails),
    path("add_author/", views.add_author),
    path("check/", views.check, name="check"),
    path("add/", views.add, name="add"),
    path("delete/<int:number>/", views.delete, name="delete"),
    path("edit/<int:number>/", views.edit, name="edit"),
]

app01.views.py

from django.shortcuts import render, HttpResponse, redirect
from django.urls import reverse
from app01.models import *


# Create your views here.


def add_publish(request):
    Publish.objects.create(
        name="人民出版社",
        city="北京",
        email="123@qq.com",
    )
    Publish.objects.create(
        name="江西出版社",
        city="江西",
        email="456@qq.com",
    )
    Publish.objects.create(
        name="南京出版社",
        city="南京",
        email="789@qq.com",
    )
    Publish.objects.create(
        name="广东出版社",
        city="深圳",
        email="135@qq.com",
    )
    return HttpResponse("OK")


def add_authordetails(request):
    Authordetails.objects.create(
        birthday="1995-5-5",
        telephone=13500000000,
        addr="广东深圳",
    )
    Authordetails.objects.create(
        birthday="1998-8-8",
        telephone=13511111111,
        addr="江西赣州",
    )
    Authordetails.objects.create(
        birthday="1997-7-7",
        telephone=13522222222,
        addr="贵州贵阳",
    )
    Authordetails.objects.create(
        birthday="1992-2-2",
        telephone=13533333333,
        addr="湖南长沙",
    )
    return HttpResponse("OK")


def add_author(request):
    Author.objects.create(
        name='alex',
        age=18,
        gender="",
        authordetail_id=4,
    )
    Author.objects.create(
        name='egon',
        age=20,
        gender="",
        authordetail_id=2,
    )
    Author.objects.create(
        name='jason',
        age=22,
        gender="",
        authordetail_id=1,
    )
    Author.objects.create(
        name='tank',
        age=24,
        gender="",
        authordetail_id=3,
    )
    return HttpResponse("OK")


def check(request):
    """
    编号、书籍名称、价格、出版日期、出版社、作者、操作
    """
    res = Book.objects.filter().all()
    l1 = list()
    for i in res:
        d1 = dict()
        d1["id"] = i.id
        d1["title"] = i.title
        d1["price"] = i.price
        d1["pub_date"] = i.pub_date
        d1["publish_name"] = Publish.objects.filter(id=i.publish_id).values("name")[0]["name"]
        l2 = list()
        # 把当前书籍的作者全部查询出来,然后放在一个列表中,通过join方法进行字符串拼接
        for x in Book.objects.filter(id=i.id).values("authors__name"):
            l2.append(x["authors__name"])
        s = ",".join(l2)
        d1["authors_name"] = s
        l1.append(d1)
    return render(request, "app01/check.html", locals())


def add(request):
    """
    名称、价格、出版日期、出版社、作者
    :param request:
    :return:
    """
    if request.method == "GET":
        res = Publish.objects.filter().all().values("name")
        res1 = Author.objects.filter().all().values("name")
        return render(request, "app01/add.html", locals())
    # 查询出所选部门的model对象,方便书籍的添加
    pub_obj = Publish.objects.filter(name=request.POST.get("publish_name")).first()
    # 将所选作者的model对象放进列表中
    l1 = list()
    for i in request.POST.getlist("authors_name"):
        au_obj = Author.objects.filter(name=i).first()
        l1.append(au_obj)
    # 书籍添加
    Book.objects.create(
        title=request.POST.get("title"),
        price=request.POST.get("price"),
        pub_date=request.POST.get("pub_date"),
        publish=pub_obj,
    )
    # 拿到当前添加的book model对象
    book_obj = Book.objects.get(title=request.POST.get("title"))
    # 进行book与author表的多对多关系绑定,*l1是列表解析
    book_obj.authors.add(*l1)
    return redirect(reverse("check"))


def delete(request, number):
    book_obj = Book.objects.filter(id=number).first()
    # 多对多关系的解除
    book_obj.authors.clear()
    Book.objects.filter(id=number).delete()
    return redirect(reverse("check"))


def edit(request, number):
    if request.method == "GET":
        res = Publish.objects.filter().all().values("name")
        res1 = Author.objects.filter().all().values("name")
        res2 = Book.objects.filter(id=number).all()
        l1 = []
        for i in res2:
            d1 = dict()
            d1["id"] = i.id
            d1["title"] = i.title
            d1["price"] = i.price
            d1["pub_date"] = i.pub_date
            d1["publish_name"] = Publish.objects.filter(id=i.publish_id).values("name")[0]["name"]
            l2 = list()
            # 把当前书籍的作者全部查询出来,然后放在一个列表中,通过join方法进行字符串拼接
            for x in Book.objects.filter(id=i.id).values("authors__name"):
                l2.append(x["authors__name"])
            s = ",".join(l2)
            d1["authors_name"] = s
            l1.append(d1)
        return render(request, "app01/edit.html", locals())
    publish_name = request.POST.get("publish_name")
    # 出版社的关联字段在书籍Book表中,所以查到相对应出版社model对象即可进行更改
    pub_obj = Publish.objects.filter(name=publish_name).first()
    Book.objects.filter(id=number).update(
        title=request.POST.get("title"),
        price=request.POST.get("price"),
        pub_date=request.POST.get("pub_date"),
        publish=pub_obj,
    )
    author_name = request.POST.getlist("authors_name")
    l3 = list()
    # # 拿到相对应作者的model对象,方便后面进行多对多关系绑定
    # for i in author_name:
    #     au_obj = Author.objects.filter(name=i).first()
    #     l3.append(au_obj)
    # book_obj = Book.objects.filter(id=number).first()
    # # 多对多关系解除
    # book_obj.authors.clear()
    # # 多对多关系重新绑定
    # book_obj.authors.add(*l3)

    # 多对多关系重新绑定
    for i in author_name:
        res = Author.objects.filter(name=i).values("id")[0]["id"]
        l3.append(str(res))
    book_obj = Book.objects.filter(id=number).first()
    book_obj.authors.set(l3)
    return redirect(reverse("check"))

templates.app01.check.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>查看书籍</title>
    <link rel="stylesheet" href="/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
    <script src="/static/jQuery3.6.js"></script>
    <script src="/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
    <style>
        table {
            margin-top: 70px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <h3>查看书籍</h3>
            <button class="btn btn-info pull-right"><a href="{% url 'add' %}">添加书籍</a></button>
            <table class="table table-bordered">
                <thead>
                <tr>
                    <th class="text-center">编号</th>
                    <th class="text-center">书籍名称</th>
                    <th class="text-center">价格</th>
                    <th class="text-center">出版日期</th>
                    <th class="text-center">出版社</th>
                    <th class="text-center">作者</th>
                    <th class="text-center">编辑操作</th>
                    <th class="text-center">删除操作</th>
                </tr>
                </thead>
                <tbody>
                {% for foo in l1 %}
                <tr class="text-center">
                <td>{{ foo.id }}</td>
                <td>{{ foo.title }}</td>
                <td>{{ foo.price }}</td>
                <td>{{ foo.pub_date|date:"Y-m-d" }}</td>
                <td>{{ foo.publish_name }}</td>
                <td>{{ foo.authors_name }}</td>
                <td><a href="{% url 'edit' foo.id %}"><button class="btn btn-sm btn-danger">编辑</button></a></td>
                <td><a href="{% url 'delete' foo.id %}"><button class="btn btn-sm btn-warning">删除</button></a></td>
                </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

templates.app01.add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加书籍</title>
    <link rel="stylesheet" href="/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
    <script src="/static/jQuery3.6.js"></script>
    <script src="/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8  col-md-offset-2">
            <h3>添加书籍</h3>
            <form action="" method="post">
                {% csrf_token %}
                <p>
                    <label for="i1">
                        书籍名称
                        <input type="text" id="i1" name="title" class="form-control">
                    </label>
                </p>
                <p>
                    <label for="i2">
                        价格
                        <input type="text" id="i2" name="price" class="form-control">
                    </label>
                </p>
                <p>
                    <label for="i3">
                        出版日期
                        <input type="date" id="i3" name="pub_date" class="form-control">
                    </label>
                </p>
                <p>
                    <label for="i4">
                        出版社
                        <select name="publish_name" id="i4" class="form-control">
                            {% for re in res %}
                                <option value="{{ re.name }}">{{ re.name }}</option>
                            {% endfor %}
                        </select>
                    </label>
                </p>
                <p>
                    <label for="i5">
                        作者
                        <select name="authors_name" id="i5" class="form-control" multiple>
                            {% for re in res1 %}
                                <option value="{{ re.name }}">{{ re.name }}</option>
                            {% endfor %}
                        </select>
                    </label>
                </p>
                <p>
                    <input type="submit" class="btn btn-success">
                </p>
            </form>
        </div>
    </div>
</div>
</body>
</html>

templates.app01.edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑书籍</title>
    <link rel="stylesheet" href="/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
    <script src="/static/jQuery3.6.js"></script>
    <script src="/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8  col-md-offset-2">
            <h3>编辑书籍</h3>
            <form action="" method="post">
                {% csrf_token %}
                <p>
                    <label for="i1">
                        书籍名称
                        <input type="text" id="i1" name="title" class="form-control" value="{{ l1.0.title }}">
                    </label>
                </p>
                <p>
                    <label for="i2">
                        价格
                        <input type="text" id="i2" name="price" class="form-control" value="{{ l1.0.price }}">
                    </label>
                </p>
                <p>
                    <label for="i3">
                        出版日期
                        <input type="date" id="i3" name="pub_date" class="form-control" value="{{ l1.0.pub_date|date:'Y-m-d' }}">
                    </label>
                </p>
                <p>
                    <label for="i4">
                        出版社
                        <select name="publish_name" id="i4" class="form-control">
                            {% for re in res %}
                                <option value="{{ re.name }}">{{ re.name }}</option>
                            {% endfor %}
                        </select>
                    </label>
                    <input type="hidden" id="i6" value="{{ l1.0.publish_name }}">
                </p>
                <p>
                    <label for="i5">
                        作者
                        <select name="authors_name" id="i5" class="form-control" multiple>
                            {% for re in res1 %}
                                <option value="{{ re.name }}">{{ re.name }}</option>
                            {% endfor %}
                        </select>
                    </label>
                    <input type="hidden" id="i7" value="{{ l2 }}">
                </p>
                <p>
                    <input type="submit" class="btn btn-success">
                </p>
            </form>
        </div>
    </div>
</div>
<script>
    let value = $("#i6").val();
    $("#i4").children("option").each(function () {
        if ($(this).val() === value) {
            $(this).prop("selected", true);
        }
    });
    let li = eval($("#i7").val());
    for (let i=0; i<li.length; i++) {
        $("#i5").children("option").each(function () {
            if ($(this).val() === li[i]) {
                $(this).prop("selected", true);
            }
        });
    }
</script>
</body>
</html>
while True: print('studying...')
原文地址:https://www.cnblogs.com/xuewei95/p/15637442.html