Django model high find(Django模型高级查询)

Django model high find

Screenshot2023-03-30 9.27.34

Model

class Employees(models.Model):
    emp_no = models.IntegerField(primary_key=True)
    birth_date = models.DateField()
    first_name = models.CharField(max_length=14)
    last_name = models.CharField(max_length=16)
    gender = models.CharField(max_length=1)
    hire_date = models.DateField()

    class Meta:
        managed = False
        db_table = 'employees'

View

group_by

**importance ** if you want to group in Django, You must use annotate with order_by and values

重要,如果你想在Django进行分组,你必须annotate和order_by同时使用。

Employees.objects.values('birth_date').annotate(count_birth=Count('birth_date')).order_by('birth_date').all()
generate sql
SELECT `employees`.`birth_date`, COUNT(`employees`.`birth_date`) AS `count_birth` FROM `employees` GROUP BY `employees`.`birth_date` ORDER BY `employees`.`birth_date` ASC

order_by

if you want to order_by in django. You can use order_by.

 employs = Employees.objects.order_by('birth_date').all()
generate sql
SELECT `employees`.`emp_no`, `employees`.`birth_date`, `employees`.`first_name`, `employees`.`last_name`, `employees`.`gender`, `employees`.`hire_date` FROM `employees` ORDER BY `employees`.`birth_date` ASC

indicates to query certain fields(只查询某些字段)

if you query all the fields。this is a time-consuming operation. (如果你想查询所有的字段,这是一个耗时的操作)

so we need fields queries. 所以我们需要指定字段查询

values
employs = Employees.objects.values('birth_date').all()
generate sql
 SELECT `employees`.`birth_date` FROM `employees`

use mysql fun

if we want to use Count, Max, or Sum and some other func。we can importing Django‘s build-in methods.

如果你想使用count,Max或者sum等其他一些函数,我们可以导入Django的一些内置方法。

count
from django.db.models import Max, Count
Employees.objects.values('birth_date').annotate(count_birth=Count('birth_date')).order_by('birth_date').all()

Generate sql

select `employees`.`birth_date`, COUNT(`employees`.`birth_date`) AS `count_birth` FROM `employees` GROUP BY `employees`.`birth_date` ORDER BY `employees`.`birth_date` ASC

use aggregate func

Django provides two aggregate function。annotate and aggregate。

annotate

Annotate allow you to alias fields and use aggreate func

example

Employees.objects.values('emp_no', ).annotate(name=F('emp_no')).all()

generate_sql

SELECT `employees`.`emp_no`, `employees`.`birth_date`, `employees`.`first_name`, `employees`.`last_name`, `employees`.`gender`, `employees`.`hire_date`, `employees`.`emp_no` AS `name` FROM `employees` LIMIT 10'
aggregate

**aggregate return a dict not a queryset ** aggregate also always the fields to to aliasd

aggratale 返回的是一个字典,并不是一个queryset。他也支持给字段取别名

Employees.objects.aaggregate(Max('birth_date'))

return result

{'birth_date__max': datetime.date(1965, 2, 1)}

complex query(复杂查找)

here’s some data。I wish to cut useing - sample, and then sort the front fields and the last fields.

这有一些数据,我希望使用-对sample进行切割,然后使用前面的字段和后面的字段进行排序。

在这里插入图片描述

example
        sample_detail = SampleDetail.objects.values('sample_no', ).annotate(
            first_field=Left('sample_no', StrIndex('sample_no', Value('-')) - 1),
            last_field=Right('sample_no', StrIndex('sample_no', Value('-')) - 1)
        ).order_by('first_field', 'last_field').all()
generage_sql
SELECT `sample_detail`.`sample_no`, LEFT(`sample_detail`.`sample_no`, (INSTR(`sample_detail`.`sample_no`, -) - 1)) AS `first_field`, RIGHT(`sample_detail`.`sample_no`, (INSTR(`sample_detail`.`sample_no`, -) - 1)) AS `last_field` FROM `sample_detail` ORDER BY `first_field` ASC, `last_field` ASC

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 创建模型 首先,我们需要创建一个模型来存储 XML 数据。假设我们要导入的 XML 数据如下: ```xml <books> <book> <title>Python for Beginners</title> <author>John Smith</author> <published_date>2020-01-01</published_date> </book> <book> <title>Python Advanced Techniques</title> <author>Jane Doe</author> <published_date>2020-02-01</published_date> </book> </books> ``` 我们可以创建一个 `Book` 模型来存储这些数据: ```python from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) published_date = models.DateField() ``` 2. 创建表单 接下来,我们需要创建一个表单来上传 XML 文件。我们可以使用 Django 的 `forms` 模块来创建表单。在 `forms.py` 文件中添加以下代码: ```python from django import forms class UploadXMLForm(forms.Form): xml_file = forms.FileField() ``` 3. 创建视图 现在我们需要创建一个视图来处理上传的 XML 文件并将其导入到数据库中。在 `views.py` 文件中添加以下代码: ```python from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import UploadXMLForm from .models import Book from xml.etree import ElementTree def upload_xml(request): if request.method == 'POST': form = UploadXMLForm(request.POST, request.FILES) if form.is_valid(): xml_file = request.FILES['xml_file'] tree = ElementTree.parse(xml_file) root = tree.getroot() for book in root.findall('book'): title = book.find('title').text author = book.find('author').text published_date = book.find('published_date').text Book.objects.create(title=title, author=author, published_date=published_date) return HttpResponseRedirect('/books/') else: form = UploadXMLForm() return render(request, 'upload_xml.html', {'form': form}) ``` 在这个视图中,我们首先检查请求的方法是否为 POST。如果是 POST,我们从表单中获取上传的 XML 文件,并使用 `ElementTree` 模块解析 XML 文件。然后,我们遍历 XML 文件中的每个 `<book>` 元素,并将其存储到数据库中。最后,我们重定向到书籍列表页面。 4. 创建模板 最后,我们需要创建一个模板来显示上传表单。在 `templates` 目录下创建一个名为 `upload_xml.html` 的文件,并添加以下代码: ```html {% extends 'base.html' %} {% block content %} <h1>Upload XML</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% endblock %} ``` 这个模板继承了一个名为 `base.html` 的基础模板,并显示一个上传表单。我们使用 Django 的模板标签 `{{ form.as_p }}` 来渲染表单。 5. 创建书籍列表视图和模板 最后,我们需要创建一个视图来显示导入到数据库中的书籍列表。在 `views.py` 文件中添加以下代码: ```python from django.shortcuts import render from .models import Book def book_list(request): books = Book.objects.all() return render(request, 'book_list.html', {'books': books}) ``` 在 `templates` 目录下创建一个名为 `book_list.html` 的文件,并添加以下代码: ```html {% extends 'base.html' %} {% block content %} <h1>Books</h1> <ul> {% for book in books %} <li>{{ book.title }} by {{ book.author }} ({{ book.published_date }})</li> {% endfor %} </ul> {% endblock %} ``` 这个模板显示了导入到数据库中的书籍列表。 6. 添加 URL 路由 最后,我们需要将视图和模板与 URL 路由关联起来。在 `urls.py` 文件中添加以下代码: ```python from django.urls import path from .views import upload_xml, book_list urlpatterns = [ path('upload-xml/', upload_xml, name='upload_xml'), path('books/', book_list, name='book_list'), ] ``` 现在,我们可以通过访问 `/upload-xml/` URL 来上传 XML 文件,并通过访问 `/books/` URL 来查看导入到数据库中的书籍列表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值