Django学习- ORM基础操作_创建数据

ORM操作:

管理器对象:

创建数据:

Django shell

想要操作模型对象,首先我们需要把它引进Django shell中

复制代码
>>> from bookstore.models import Book
>>> b1 = Book.objects.create(title='AI', pub='清华大学出版社', price= 20,market_price = 25)
>>> b2 = Book(title='爱',pub='清华大学出版社',price=70,market_price = 50)
>>> b2.save()

查询数据:

例子:

第一步:在django学习下的settings中添加bookstore

python 复制代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'music',
    # 'news',
    # 'sport',
    'bookstore'
]

第二步:在 django学习下的urls添加bookstore

python 复制代码
from django.contrib import admin
from django.urls import path,include,re_path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # 主路由链接需要加/
    #path('music/',include("music.urls")),
    #path('sport/',include("sport.urls")),
    #path('news/',include("news.urls")),
    path('bookstore/',include('bookstore.urls'))
]

第三步:在bookstore的模型和视图以及url

urls.py:

python 复制代码
from django.urls import path
from . import views

urlpatterns = [
    path('all_book', views.all_books, name='all_book')
]

views.py:

python 复制代码
from django.shortcuts import render

from bookstore.models import Book


# Create your views here.

def all_books(request):
    books = Book.objects.all()
    return render(request, 'bookstore/all_book.html',locals())

all_book.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>查看所有书籍</title>
</head>
<body>
<table >
    <tr>
        <th>id</th>
        <th>title</th>
        <th>pub</th>
        <th>price</th>
        <th>market_price</th>
        <th>op</th>
    </tr>
    {% for book in books %}
        <tr>
            <td>{{ book.id }}</td>
            <td>{{ book.title }}</td>
            <td>{{ book.pub }}</td>
            <td>{{ book.price }}</td>
            <td>{{ book.market_price }}</td>
            <td>
                <a href="">删除</a>
                <a href="">更新</a>
            </td>
        </tr>
    {% endfor %}
</table>
</body>
</html>

条件查询:

查询谓词:

修改数据:

删除操作:

单个删除:

批量删除:

伪删除:

相关推荐
点云-激光雷达-Slam-三维牙齿2 小时前
速度起飞 笔记本电脑6G显卡llama运行Qwen3.6 35BA3B MTP 大模型
人工智能·python·电脑·llama
言乐62 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
青山是哪个青山8 小时前
LangChain 学习笔记(四):Message 与提示词模板
笔记·学习·langchain
小白勇闯网安圈8 小时前
Django 响应对象、文件上传与类视图
数据库·django·sqlite
从零开始学习人工智能9 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
hsjiasb9 小时前
FreeRTOS学习(二十六)——动态内存管理heap_1到heap_5
stm32·单片机·学习·学习笔记·freertos
崇子嵘9 小时前
基于zynqMP15eg的linux驱动学习
学习
卷无止境10 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha131410 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教10 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi