首先,编写模型类:models.py

from django.db import models

# Create your models here.

class Book(models.Model):
    book_name = models.CharField('书名', max_length=80)
    book_publisher = models.CharField('出版社', max_length=80)
    book_price = models.DecimalField('价格', max_digits=8, decimal_places=2)

使用Django Shell:

(venv) adamhuan:djangoProject_for_Learning/ $ python manage.py shell                                                                                         [15:52:21]
Python 3.10.0 (v3.10.0:b494f5935c, Oct  4 2021, 14:59:19) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 
>>> from book.models import *
>>> 
>>> book = Book.objects.create(book_name="乔布斯传",book_price=45.6,book_publisher="清华大学出版社")
(0.005) INSERT INTO `book_book` (`book_name`, `book_publisher`, `book_price`) VALUES ('乔布斯传', '清华大学出版社', 45.600000); args=['乔布斯传', '清华大学出版社', Decias=default
>>> 

获取Django写入与查询数据时候的SQL语句:

>>> print(Book.objects.all().query)
SELECT `book_book`.`id`, `book_book`.`book_name`, `book_book`.`book_publisher`, `book_book`.`book_price` FROM `book_book`
>>> 
>>> print(Book.objects.order_by('-book_name').query)
SELECT `book_book`.`id`, `book_book`.`book_name`, `book_book`.`book_publisher`, `book_book`.`book_price` FROM `book_book` ORDER BY `book_book`.`book_name` DESC
>>> 
>>> print(Book.objects.order_by('-book_name').values('book_publisher').query)
SELECT `book_book`.`book_publisher` FROM `book_book` ORDER BY `book_book`.`book_name` DESC
>>> 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

隐藏
变装