django
orm
from django.db import models
# create your models here.
class
publisher
(models.model):
name = models.charfield(max_length=32)
city = models.charfield(max_length=32)
def__str__
(self):
return self.name
class
book
(models.model):
title = models.charfield(max_length=32)
publish_date = models.datefield(auto_now_add=true)
price = models.decimalfield(max_digits=5, decimal_places=2)
publisher = models.foreignkey(to="publisher")
def__str__
(self):
return self.title
class
author
(models.model):
name = models.charfield(max_length=32)
age = models.integerfield()
phone = models.integerfield()
books = models.manytomanyfield(to="book", related_name="authors")
detail = models.onetoonefield(to="authordetail")
def__str__
(self):
return self.name
class
authordetail
(models.model):
bobby = models.charfield(max_length=32)
addr = models.charfield(max_length=128)
import os
import sys
if __name__ == '__main__':
os.environ.setdefault("django_settings_module", "ormday70.settings")
import django
django.setup()
# 查詢所有書名裡包含沙河的書
ret = models.book.objects.filter(title__contains="沙河")
print(ret)
# 查詢所有出版日期是2023年的書
ret = models.book.objects.filter(publish_date__year=2018)
print(ret)
# 查詢**大於10元的書
ret = models.book.objects.filter(price__gt=10)
print(ret)
# 找到在沙河的出版社
ret = models.publisher.objects.filter(city="沙河")
print(ret)
# distinct
# 查所有書關聯的出版社
ret = models.book.objects.all().values_list("publisher__name")
print(ret)
# distinct去重
print(ret.distinct())
# 將所有的書按照**倒敘排序
# 預設排序
ret = models.book.objects.all().order_by("price")
print(ret)
# 倒序
print(ret.reverse())
# 同時,支援使用減號表示倒序排序
ret = models.book.objects.all().order_by("-price")
print(ret)
# 查詢書名是沙河異聞錄的書的出版社的city
ret = models.book.objects.filter(title="沙河異聞錄").values_list("publisher__city")
print(ret)
# 查詢書名是沙河異聞錄的書的作者的愛好(誇兩張表)
ret = models.book.objects.filter(title=
"沙河異聞錄"
Python day70 ORM查詢練習
orm查詢練習 import osimport sysif name main 載入djang00專案的配置資訊 os.environ.setdefault django settings module ormday69.settings 匯入django,並啟動django專案 import dj...
基於物件的orm跨表查詢再練習
model.py from django.db import models create your models here.class book models.model nid models.autofield primary key true title models.charfield max...
ORM正向和反向查詢
表結構 from django.db import models create your models here.class publisher models.model id models.autofield primary key true name models.charfield max l...