- Django 2 by Example
- Antonio Melé
- 220字
- 2021-06-25 21:19:01
Creating model managers
As we previously mentioned, objects is the default manager of every model that retrieves all objects in the database. However, we can also define custom managers for our models. We will create a custom manager to retrieve all posts with the published status.
There are two ways to add managers to your models: you can add extra manager methods or modify initial manager QuerySets. The first method provides you with a QuerySet API such as Post.objects.my_manager(), and the latter provides you with Post.my_manager.all(). The manager will allow us to retrieve posts using Post.published.all().
Edit the models.py file of your blog application to add the custom manager:
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
# ...
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager.
The get_queryset() method of a manager returns the QuerySet that will be executed. We override this method to include our custom filter in the final QuerySet. We have defined our custom manager and added it to the Post model; we can now use it to perform queries. Let's test it.
Start the development server again with the following command:
python manage.py shell
Now, you can retrieve all published posts whose title starts with Who using the following command:
Post.published.filter(title__startswith='Who')
- FreeSWITCH 1.2
- CorelDRAW X6 中文版圖形設計實戰從入門到精通
- 網管員典藏書架:網絡管理與運維實戰寶典
- Hands-On Industrial Internet of Things
- Building RESTful Web Services with Spring 5(Second Edition)
- 正在爆發的互聯網革命
- 數字通信同步技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- TD-LTE無線網絡規劃與設計
- Echo Quick Start Guide
- 6G無線網絡空口關鍵技術
- 網管第一課:網絡操作系統與配置管理
- Dart Cookbook
- Laravel Application Development Cookbook
- 黑客與反黑工具使用詳解
- 路由與交換技術