• Django 通过 ORM 实现表的CRUD


    Django 通过 ORM 实现表的CRUD

    单表的创建
    1. 修改 setting.py 文件
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': '数据库名称',
            'USER': '用户名',
            'PASSWORD': '密码',
            'HOST': '127.0.0.1',
            'PORT': '3306',
        }
    }
    
    1. 修改应用下面对应的models.py 文件
    class Book(models.Model):
        nid = models.AutoField(primary_key=True)  # 表ID 自增主键
        title = models.CharField(max_length=32)  # 字符串,最大长度为32
        price = models.DecimalField(max_digits=8, decimal_places=2)  # 小数,最多8位,小数点最多2位
        publish = models.CharField(max_length=32)
        pub_date = models.DateTimeField()
    
    1. 修改在与 setting.py 同级的目录下的 _ init_.py 文件
    import pymysql
    
    pymysql.install_as_MySQLdb()
    
    1. 执行以下脚本在应用下创建 migrations 包以及相应的类
    python manage.py makemigrations
    
    1. 执行以下脚本会在数据库中创建 INSTALLED_APPS 中所有对应的数据表
    python manage.py migrate
    
    Django 数据的插入(PS:要先完成表的生成)
    • 修改 urls.py 文件
    from django.contrib import admin
    from django.urls import path
    from vedio import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('add/', views.add),
    ]
    
    • 修改 views.py 文件
    from django.shortcuts import render,HttpResponse,redirect
    from vedio.models import Book
    
    def add(request):
    
        # 方法一
        """
        book = Book(title="Django", price=123, pub_date="2019-10-06", publish="人民出版社")
        book.save()
        """
        # 方法二
        Book.objects.create(title="Think PHP", price=123, pub_date="2019-10-06", publish="人民出版社")
        # 方法三
        """
        Book.objects.create(**request.POST.dict())
        PS:request.POST 要删除 {{ csrf-token }} 引进了的变量
        """
        return HttpResponse("OK")
    
    Django 数据的查询,删除,修改
    • 修改 views.py 文件
    from django.shortcuts import render,HttpResponse,redirect
    from vedio.models import Book
    
    def books(request):
        # books = Book.objects.all()  # 返回所有记录
        books = Book.objects.filter(title="Think PHP")  # 查询标题等于 Think PHP的所有记录
        # Book.objects.filter(title="Think PHP").delete()  # 删除标题为 Think PHP的所有条记录
        # Book.objects.filter(nid=1).update(price=120)  # 更新 nid=1 这条数据的price
        return render(request, "books.html", locals())
    
    • 修改 urls.py 文件
    from django.contrib import admin
    from django.urls import path
    from vedio import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('books/', views.books),
    ]
    
    Django 查询深入
    from django.shortcuts import render,HttpResponse,redirect
    from vedio.models import Book
    
    def books(request):
    
        # all()
        # books = Book.objects.all()  # 返回所有记录
    
        # filter()
        # books = Book.objects.filter(title="Think PHP")  # 查询标题等于 Think PHP的所有记录
        # books = Book.objects.filter(title="Think PHP", nid=2)  # 查询标题等于 Think PHP 并且 nid = 2 的所有记录
    
        # get()
        # books = Book.objects.get(title="Think PHP")  # 查询标题等于 Think PHP 的一条记录,大于1条或1条都没有将报错
    
        # first() last()
        # books = Book.objects.all().first()  # 返回 queryset 的第一个 model 对象
        # books = Book.objects.all().last()  # 返回 queryset 的最后一个 model 对象
    
        # exclude()
        # books = Book.objects.exclude(title="Django")  # 查询 title 不等于 Django 的 querySet
    
        # order_by()
        # books = Book.objects.all().order_by('price')  # 根据price 升序
        # books = Book.objects.all().order_by('-price')  # 根据price 降序
    
        # count()
        # books_num = Book.objects.all().count()  # 返回书籍的个数
    
        # reverse()
        # books = Book.objects.all().reverse()  # 逆序
    
        # exits()
        # is_exits = Book.objects.all().exists()  # 判断数据表是否有数据
    
        # values()
        # ret = Book.objects.all().values('title', 'price')  # 取 title price 的数据,返回一个列表,列表里面的数据是字典
    
        # values_list()
        # ret = Book.objects.all().values_list('title', 'price')  # 取 title price 的数据,返回一个列表,列表里面的数据是元组
    
        # distinct()
        # books = Book.objects.all().values("title").distinct()  # 对 title 中的数据进行去重
    
        # __gt __lt __gte __lte
        # books = Book.objects.filter(price__gt=200)  # 查询 price 大于200 的数据
        # books = Book.objects.filter(price__gte=200)  # 查询 price 大于等于200 的数据
        # books = Book.objects.filter(price__lt=200)  # 查询 price 小于200 的数据
        # books = Book.objects.filter(price__lte=200)  # 查询 price 小于等于200 的数据
    
        # __startswith __istartswith __contains __icontains
        # books = Book.objects.filter(title__startswith="Think")  # 查询 title 以 Think 开头的数据
        # books = Book.objects.filter(title__istartswith="think")  # 查询 title 以 Think 开头的数据,不区分大小写
        # books = Book.objects.filter(title__contains="Think")  # 查询 包含 Think 的数据
    
        return render(request, "books.html", locals())
    
    Django 一对多表的创建
    • 修改应用下的models.py 文件
    from django.db import models
    class Book(models.Model):
        nid = models.AutoField(primary_key=True)  # 表ID 自增主键
        title = models.CharField(max_length=32)  # 字符串,最大长度为32
        price = models.DecimalField(max_digits=8, decimal_places=2)  # 小数,最多8位,小数点最多2位
        pub_date = models.DateTimeField()
        publish = models.ForeignKey(to="Publish", on_delete=models.CASCADE)  # on_delete=models.CASCADE 指定级联删除
    
    
    class Publish(models.Model):
        nid = models.AutoField(primary_key=True)
        name = models.CharField(max_length=32)
        email = models.CharField(max_length=32, null=True)  # null=True表示该字段可以为空
    
    Django 多对多表的创建
    • 修改应用下的 models.py 文件
    from django.db import models
    class Book(models.Model):
        nid = models.AutoField(primary_key=True)  # 表ID 自增主键
        title = models.CharField(max_length=32)  # 字符串,最大长度为32
        price = models.DecimalField(max_digits=8, decimal_places=2)  # 小数,最多8位,小数点最多2位
        pub_date = models.DateTimeField()
        publish = models.ForeignKey(to="Publish", on_delete=models.CASCADE)  # on_delete=models.CASCADE 指定级联删除
        authors = models.ManyToManyField(to="Author")  # 指定多对多
        
    class Author(models.Model):
        nid = models.AutoField(primary_key=True)
        name = models.CharField(max_length=32)
        age = models.IntegerField()
        email = models.CharField(max_length=32)
    
    Django 一对一表的创建
    • 修改应用下的 models.py 文件
    from django.db import models
    class Author(models.Model):
        nid = models.AutoField(primary_key=True)
        name = models.CharField(max_length=32)
        age = models.IntegerField()
        email = models.CharField(max_length=32)
        ad = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE)
    
    
    class AuthorDetail(models.Model):
        addr = models.CharField(max_length=32)
        tel = models.IntegerField()
    
    Django 一对多数据的插入
    Book.objects.create(title="Python")
    
    Django 多对多数据的插入
    book = Book.objects.create(title="Django")
    
    # 方法一
    zp = Author.objects.filter(name="zp").first()
    mcx = Author.objects.filter(name="mcx").first()
    book.authors.add(zp, mcx)
    
    # 方法二
    book.authors.add(1, 2)
    
    # 方法三
    book.authors.add(*[1, 2])
    
    Django 多对多数据的解除绑定
    book = Book.objects.filter(title="Django").first()
    mcx = Author.objects.filter(name="mcx").first()
    book.authors.remove(mcx)  # 删除 与 book 关联的 mcx
    book.authors.clear()  # 删除 与 book 关联的所有作者
    
    Django 多对多数据的解除再绑定
    book = Book.objects.filter(title="Django").first()
    
    # 方法一
    book.authors.clear()
    book.authors.add(1)
    
    # 方法二
    book.authors.set(1)
    
  • 相关阅读:
    USACO 3.3 A Game
    USACO 3.3 Camelot
    USACO 3.3 Shopping Offers
    USACO 3.3 TEXT Eulerian Tour中的Cows on Parade一点理解
    USACO 3.3 Riding the Fences
    USACO 3.2 Magic Squares
    USACO 3.2 Stringsobits
    USACO 3.2 Factorials
    USACO 3.2 Contact
    USACO 3.1 Humble Numbers
  • 原文地址:https://www.cnblogs.com/GetcharZp/p/11630970.html
Copyright © 2020-2023  润新知