Django ORM 练习题

代码目录结构

|-- djago_study
|-- manage.py
|-- test_django.py
|-- app01
| |-- admin.py
| |-- apps.py
| |-- models.py
| |-- tests.py
| |-- views.py
| |-- init.py
| |-- migrations
| |-- 0001_initial.py
| |-- init.py
|-- djago_study
| |-- settings.py
| |-- urls.py
| |-- wsgi.py
| |-- init.py
|-- templates

数据表

app01_author

idnameagephonedetail_id
1格非2018900000001
2迈克尔·汤普森2213100000002

app01_author2book

idauthor_idbook_id
111
222

app01_authordetail

idhobbyaddr
1踢毽子北京
2看书上海
3逛街广州

app01_book

idtitlepublish_datepricepublisher_id
1沙河异闻录2019-09-29100.001
2养育男孩2019-09-0380.002
3沙河三部曲2018-10-2470.002

app01_publisher

idnamecity
1北京十月文艺出版社北京
2中信出版社北京

django_migrations

idappnameapplied
1app010001_initial2019-09-29 07:49:04.899704

./test_django.py

import os


def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djago_study.settings')
    import django
    django.setup()

    from app01 import models
    ret = models.Book.objects.filter(title__contains="沙河")
    print("查找包含沙河的书", ret)
    ret = models.Book.objects.filter(publish_date__year=2018)
    print("查找出版日期2018的书", ret)
    ret = models.Book.objects.filter(price__gt=10)
    print("查找价格大于10的书", ret)
    ret = models.Publisher.objects.filter(city__contains="北京")
    print("查找在北京的出版社", ret)

    ret = models.Book.objects.all().values_list("publisher__name")
    print("查所有书关联的出版社", ret, "去重后的结果集", ret.distinct())  # distinct 去重

    ret = models.Book.objects.all().order_by("price").reverse()
    print("讲所有书,按照价格排序 方法一", ret)
    ret = models.Book.objects.all().order_by("-price").reverse()
    print("讲所有书,按照价格排序 方法二", ret)  # - 负号表示倒序

    ret = models.Book.objects.filter(title="沙河异闻录").values("publisher__city")
    print("查找书籍沙河异闻录出版社的所在的城市", ret)

    ret = models.Book.objects.filter(title="沙河异闻录").values("author__detail__hobby")
    print("查找书籍是沙河异闻录作者的爱好", ret)


if __name__ == '__main__':
    main()

./app01/models.py

# Create your models here.
from django.db import models


# 出版社
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)
    # 创建外键,关联publish
    publisher = models.ForeignKey(to="Publisher", on_delete=models.CASCADE)

    def __str__(self):
        return "书名 {} 价格 {}".format(self.title, self.price)


# 作者
class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    phone = models.IntegerField()
    # 通过through指定第三张表
    # through_fields指定表字段
    books = models.ManyToManyField(to="Book", through="Author2Book", through_fields=("author", "book"))

    detail = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE)

    def __str__(self):
        return self.name


# 自己动手 创建作者和书关联的第三张表
# 此时 在ORM层面
class Author2Book(models.Model):
    id = models.AutoField(primary_key=True)
    # 作者id
    author = models.ForeignKey(to="Author", on_delete=models.CASCADE)
    # 书id
    book = models.ForeignKey(to="Book", on_delete=models.CASCADE)

    class Meta:
        # 建立唯一约束, 保证不可重复
        unique_together = ("author", "book")


# 作者详情
class AuthorDetail(models.Model):
    # 爱好
    hobby = models.CharField(max_length=32)
    # 地址
    addr = models.CharField(max_length=128)

整套源码下载地址
https://www.lanzous.com/i6hew4d

相关资料

F查询操作
https://docs.djangoproject.com/en/2.2/ref/models/expressions/#django.db.models.F
双下划线方法操作
https://www.dev2qa.com/what-does-double-underscore-__-means-in-django-model-queryset-objects-filter-method/
Q查询操作
https://docs.djangoproject.com/en/2.2/ref/models/querysets/#q-objects
聚合查询示例
https://docs.djangoproject.com/en/2.2/topics/db/aggregation/
查询教程
https://docs.djangoproject.com/en/2.2/topics/db/queries/
Model字段 AutoField BigIntegerField
https://docs.djangoproject.com/zh-hans/2.2/ref/models/fields/#decimalfield
ORM那些相关操作
https://www.cnblogs.com/liwenzhou/p/8660826.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值