练习|Django-多表

models.py

from django.db import models

# Create your models here.
class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name=models.CharField( max_length=32)
    age=models.IntegerField()

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

class Book(models.Model):

    nid = models.AutoField(primary_key=True)
    title = models.CharField( max_length=32)
    publishDate=models.DateField()
    price=models.DecimalField(max_digits=5,decimal_places=2) # 999.99

    # 与Publish建立一对多的关系,外键字段建立在多的一方
    publish=models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE)
    # 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表
    authors=models.ManyToManyField(to='Author',)

urls.py

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

from book import views

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('books/add/$', views.add_book),
    re_path('books/$', views.books),
    re_path('books/(\d+)/change/$', views.change_book),
    re_path('books/(\d+)/delete/$', views.delete_book),
]

在settings里边

views.py

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

from .models import Publish,Author,Book
def add_book(request):

    if request.method=="POST":
        title=request.POST.get("title")
        price=request.POST.get("price")
        pub_date=request.POST.get("pub_date")
        publish_id=request.POST.get("publish_id")
        authors_id_list=request.POST.getlist("authors_id_list") # checkbox,select

        book_obj=Book.objects.create(title=title,price=price,publishDate=pub_date,publish_id=publish_id)
        print(authors_id_list) # ['2', '3']

        book_obj.authors.add(*authors_id_list)

        return HttpResponse("success")

    publish_list=Publish.objects.all()
    author_list=Author.objects.all()

    return render(request,"addbook.html",{"author_list":author_list,"publish_list":publish_list})

def books(request):
    book_list = Book.objects.all()
    return render(request, "book.html",{"book_list":book_list})

def change_book(request,edit_book_id):
    edit_book_obj = Book.objects.filter(pk = edit_book_id).first()
    if request.method == 'POST':
        title = request.POST.get('title')
        price = request.POST.get('price')
        pub_date = request.POST.get('pub_date')
        publish_id = request.POST.get('publish_id')
        authors_id_list = request.POST.getlist('authors_id_list')

        Book.objects.filter(pk=edit_book_id).update(title=title, price=price,publishDate=pub_date, publish_id=publish_id)
        # edit_book_obj.authors.clear()
        # edit_book_obj.authors.add(*authors_id_list)
        edit_book_obj.authors.set(authors_id_list)

        return redirect("/books/")


    publish_list = Publish.objects.all()
    author_list = Author.objects.all()

    return render(request, 'editbook.html',{"edit_book_obj":edit_book_obj, "publish_list":publish_list, "author_list":author_list})

def delete_book(request, delete_book_id):
    Book.objects.filter(pk=delete_book_id).delete()
    return redirect("/books/")

addbook.html(添加书籍)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body>

<h3>添加书籍</h3>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <form action="" method="post">
                {% csrf_token %}
                <div class="form-group">
                    <label for="">名称</label>
                    <input type="text" name="title" class="form-control" value="">
                </div>

                <div class="form-group">
                    <label for="">价格</label>
                    <input type="text" name="price" class="form-control">
                </div>

                <div class="form-group">
                    <label for="">出版日期</label>
                    <input type="date" name="pub_date" class="form-control">
                </div>

                <div class="form-group">
                    <label for="">出版社</label>
                    <select name="publish_id" id="" class="form-control">
                        {% for publish in publish_list %}
                            <option value="{{ publish.pk }}">{{ publish.name }}</option>
                        {% endfor %}
                    </select>
                </div>

                <div class="form-group">
                    <label for="">作者</label>
                    <select type="text" name="authors_id_list" multiple class="form-control">
                        {% for author in author_list %}
                            <option value="{{ author.pk }}">{{ author.name }}</option>
                        {% endfor %}

                    </select>
                </div>
                <input type="submit" class="btn btn-default">

            </form>
        </div>
    </div>
</div>


</body>
</html>

book.html(查看书籍)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body>

<h3>查看书籍</h3>

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2"> {# 边框、悬浮时变色、条纹编码 #}
            <a href="/books/add" class="btn btn-primary">添加书籍</a>
            <table class="table table-bordered table-hover table-striped">
                <thead>
                <tr>
                    <th>编号</th>
                    <th>书籍名称</th>
                    <th>价格</th>
                    <th>出版日期
                    <th>出版社</th>
                    <th>作者</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                {% for book in book_list %}
                    <tr>
                        <td>{{ forloop.counter }}</td>
                        <td>{{ book.title }}</td>
                        <td>{{ book.price }}</td>
                        <td>{{ book.publishDate|date:'Y-m-d' }}</td>
                        <td>{{ book.publish.name }}</td>
                        <td>
                            {% for author in book.authors.all %}
                                {% if forloop.last %}
                                    <span>{{ author.name }}</span>
                                {% else %}
                                    <span>{{ author.name }}</span>,
                                {% endif %}
                            {% endfor %}

                        </td>
                        <td>
                            <a href="/books/{{ book.pk }}/change/" class="btn btn-warning">编辑</a>
                            <a href="/books/{{ book.pk }}/delete/" class="btn btn-danger">删除</a>

                        </td>
                    </tr>
                {% endfor %}

                </tbody>
            </table>
        </div>
    </div>
</div>


</body>
</html>

editbook.html(编辑书籍)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body>

<h3>编辑书籍</h3>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <form action="" method="post">
                {% csrf_token %}
                <div class="form-group">
                    <label for="">名称</label>
                    <input type="text" name="title" class="form-control" value="{{ edit_book_obj.title }}">
                </div>

                <div class="form-group">
                    <label for="">价格</label>
                    <input type="text" name="price" class="form-control" value="{{ edit_book_obj.price }}">
                </div>

                <div class="form-group">
                    <label for="">出版日期</label>
                    <input type="date" name="pub_date" class="form-control"
                           value="{{ edit_book_obj.publishDate|date:'Y-m-d' }}">
                </div>

                <div class="form-group">
                    <label for="">出版社</label>
                    <select name="publish_id" id="" class="form-control">
                        {% for publish in publish_list %}
                            <option selected value="{{ publish.pk }}">{{ publish.name }}</option>
                            {% if edit_book_obj.publish == publish %}
                            {% else %}
                                <option value="{{ publish.pk }}">{{ publish.name }}</option>
                            {% endif %}


                        {% endfor %}
                    </select>
                </div>

                <div class="form-group">
                    <label for="">作者</label>
                    <select type="text" name="authors_id_list" multiple class="form-control">
                        {% for author in author_list %}
                            {% if author in edit_book_obj.authors.all %}
                                <option selected value="{{ author.pk }}">{{ author.name }}</option>
                            {% else %}
                                <option value="{{ author.pk }}">{{ author.name }}</option>
                            {% endif %}
                        {% endfor %}

                    </select>
                </div>
                <input type="submit" class="btn btn-default">

            </form>
        </div>
    </div>
</div>


</body>
</html>

猜你喜欢

转载自www.cnblogs.com/shengyang17/p/9695608.html