Django Querysets: Working with Objects in Your Database
Django features a built-in 'ORM' (Object-Relational Mapping) system that enables you to interact with your database using Python objects.
The core of the ORM is the 'model' class, defining the structure of your data. Once you've defined a model, you can create and manipulate 'querysets', which are collections of objects matching specific criteria.
Some common operations you can perform on querysets include:
- Filtering: Selecting objects meeting certain criteria (e.g., all products with a price less than $10)
- Ordering: Sorting objects by one or more fields (e.g., all products ordered by name)
- Aggregation: Calculating summary information about a group of objects (e.g., the total revenue generated by all products)
- Annotation: Adding additional information to each object in a queryset (e.g., the number of reviews for each product)
Here's an example of how you might use querysets to interact with a simple 'blog' app:
# models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
# views.py
from django.shortcuts import render
from .models import Post
def post_list(request):
# get all posts, ordered by publication date
posts = Post.objects.order_by('-pub_date')
# render the list of posts in a template
return render(request, 'blog/post_list.html', {'posts': posts})
In this example, we define two models: 'Author' and 'Post'. Each post belongs to an author, and has a title, body, and publication date.
In the view function 'post_list', we utilize the 'objects' manager on the 'Post' model to obtain a queryset of all posts, ordered by publication date in descending order. We then pass this queryset to a template for rendering as HTML.
原文地址: https://www.cveoy.top/t/topic/oFlh 著作权归作者所有。请勿转载和采集!