IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> Python django之一对多与多对多查询笔记(test) -> 正文阅读

[Python知识库]Python django之一对多与多对多查询笔记(test)

models.py

from django.db import models


# 作者详情表
class AuthorDetail(models.Model):
    nid = models.AutoField(primary_key=True)
    birthday = models.DateField()
    telephone = models.BigIntegerField()
    address = models.CharField(max_length=64)

    class Meta(object):
        db_table = 'authordetail'


#
class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    authordetail = models.OneToOneField(to='AuthorDetail',to_field='nid',on_delete=models.CASCADE)

    class Meta(object):
        db_table = 'author'


# 出版社表
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 Meta(object):
        db_table = 'publish'


# 出版社表
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)

    # 一对多
    # 关联字段 django会自动拼接id publish --->? publish_id
    publish = models.ForeignKey(to='Publish', to_field='nid',on_delete=models.CASCADE,null=True)  # 外键值可以为空
    """ 
    create table book (
    id INT primary key auto_increment,
    title varchar(32),
    price DECIMAL(8,2),
    publishDate Date,
    publish_id INT,
    foregin key(publish_id) references publish(nid)
    )
    """

    # 多对多,执行完创建第三张表:book2author
    authors = models.ManyToManyField(to='Author')

    """
    mysql> desc book_authors;
    +-----------+------+------+-----+---------+----------------+
    | Field     | Type | Null | Key | Default | Extra          |
    +-----------+------+------+-----+---------+----------------+
    | id        | int  | NO   | PRI | NULL    | auto_increment |
    | book_id   | int  | NO   | MUL | NULL    |                |
    | author_id | int  | NO   | MUL | NULL    |                |
    +-----------+------+------+-----+---------+----------------+
    """

    class Meta(object):
        db_table = 'book'


views.py

from django.shortcuts import render,HttpResponse
from .models import *


def index(request):

    # ----------------------------绑定一对多的关系------------------------------------#

    # ret = Publish.objects.create(name='人民出版社', email='15532634791@163.com',city='北京')
    # ret = Publish.objects.create(name='河北出版社', email='wangze@163.com',city='河北')
    # # print(ret)
    #
    # # 方式一
    # book_obj = Book.objects.create(title='红楼梦',publishDate='2001-04-01',price=200,publish_id=1)
    # book_obj = Book.objects.create(title='西游记',publishDate='2001-04-01',price=200,publish_id=1)
    # # publish_id 为数据表中的字段
    # print(book_obj.title)

    # 方式二
    # pub_obj = Publish.objects.filter(nid=1).first()
    # print(pub_obj.name)
    # book_obj = Book.objects.create(title='水浒传', publishDate='2001-04-01', price=200, publish=pub_obj)
    # print(book_obj.title)
    # print(book_obj.publish)         # 为Publish对象Publish object (1)
    # print(book_obj.publish.email)   # 为Publish对象Publish object (1)
    # print(book_obj.publish_id)

    # ret = Book.objects.filter(title='水浒传').distinct().first()
    # print(ret[0].nid)
    # print(ret[0].publishDate)
    # print(ret.publish.email)  # 拿到关联的出版社对象 publish,外键值可以获取对象值

    # ----------------------------绑定多对多的关系------------------------------------#

    # book_obj = Book.objects.create(title='金瓶梅3', publishDate='2001-04-01', price=200, publish_id=1)
    pass
    """
    MariaDB [orm]> select * from book;
    +-----+------------+-------------+--------+------------+
    | nid | title      | publishDate | price  | publish_id |
    +-----+------------+-------------+--------+------------+
    |   1 | 红楼梦     | 2001-04-01  | 200.00 |          1 |
    |   2 | 西游记     | 2001-04-01  | 200.00 |          1 |
    |   3 | 水浒传     | 2001-04-01  | 200.00 |          1 |
    |   4 | 红楼梦     | 2001-04-01  | 200.00 |          1 |
    |   5 | 西游记     | 2001-04-01  | 200.00 |          1 |
    |   6 | 水浒传     | 2001-04-01  | 200.00 |          1 |
    |   7 | 金瓶梅     | 2001-04-01  | 200.00 |          1 |
    |   8 | 金瓶梅1    | 2001-04-01  | 200.00 |          1 |
    |   9 | 金瓶梅2    | 2001-04-01  | 200.00 |          1 |
    +-----+------------+-------------+--------+------------+
    """
    pass
    # AuthorDetail.objects.create(nid=1,birthday='2004-03-02',telephone=110,address='北京')
    # AuthorDetail.objects.create(nid=2,birthday='2005-03-02',telephone=911,address='南京')
    # Author.objects.create(nid=1,name='alex',age=33,authordetail_id=1)
    # Author.objects.create(nid=2,name='egon',age=43,authordetail_id=2)
    """
    MariaDB [orm]> select * from author;
    +-----+------+-----+-----------------+
    | nid | name | age | authordetail_id |
    +-----+------+-----+-----------------+
    |   1 | alex |  33 |               1 |
    |   2 | egon |  43 |               2 |
    +-----+------+-----+-----------------+
    """

    # alex = Author.objects.get(name='alex')
    # egon = Author.objects.get(name='egon')
    # print(egon.name) # egon

    # 绑定多对多关系的API接口
    # book_obj.authors.add(alex,egon)  # 找到 book 和 authors 的关联表
    # book_obj.authors.add(1,2,3)  # 找到 book 和 authors 的关联表
    # book_obj.authors.add(*[1,2,3])  # 找到 book 和 authors 的关联表

    """
    MariaDB [orm]> select * from book_authors;
    +----+---------+-----------+
    | id | book_id | author_id |
    +----+---------+-----------+
    |  3 |       9 |         1 |
    |  4 |       9 |         2 |
    +----+---------+-----------+
    """


    # 解除多对多关系的API
    #  select nid from book where title='金瓶梅2'; nid =9
    book = Book.objects.filter(nid=10).first()
    print(book)
    # book.authors.remove(1,2)  # DELETE FROM `book_authors` WHERE (`book_authors`.`book_id` = 9 AND `book_authors`.`author_id` IN (1, 2));

    pass
    """
    MariaDB [orm]> select * from book_authors;
    Empty set (0.000 sec)
    """
    pass

    # book.authors.remove(*[1,2])
    # book.authors.clear() # 全部清空

    print(book.authors.all()) # 与这本书相关的所有作者对象1集合,queryset类型
    # <QuerySet [<Author: Author object (1)>, <Author: Author object (2)>]>
    ret = book.authors.all().values('name')
    print(ret) # <QuerySet [{'name': 'alex'}, {'name': 'egon'}]>
    return HttpResponse('OK')





  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2021-08-04 11:09:46  更:2021-08-04 11:10:36 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/12 3:58:54-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码