在Django中,您可以向查询集中添加一个方法吗? [英] In Django, can you add a method to querysets?

查看:131
本文介绍了在Django中,您可以向查询集中添加一个方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,如果我有一个模型类,例如

In Django, if I have a model class, e.g.

from django.db import models

class Transaction(models.Model):
    ...

然后如果我想向模型添加方法,存储例如相当复杂的过滤器,我可以添加一个自定义模型管理器,例如

then if I want to add methods to the model, to store e.g. reasonably complex filters, I can add a custom model manager, e.g.

class TransactionManager(models.Manager):

    def reasonably_complex_filter(self):
        return self.get_query_set().filter(...)


class Transaction(models.Model):
    objects = TransactionManager()

然后我可以做:

>>> Transaction.objects.reasonably_complex_filter()

有没有办法我可以添加一个可以链接的自定义方法到模型的查询集结尾?

Is there any way I can add a custom method that can be chained to the end of a query set from the model?

ie添加自定义方法,使我可以这样做:

i.e. add the custom method in such a way that I can do this:

>>> Transaction.objects.filter(...).reasonably_complex_filter()


推荐答案

您需要向最终最终添加的 QuerySet 添加方法。因此,您需要创建并使用 QuerySet 子类,具有您要定义此功能的任何方法。

You need to add methods to the QuerySet which you eventually end up with. So you need to create and use a QuerySet subclass which has the methods you define wherever you want this functionality.

我发现这个教程解释了如何做到这一点,以及为什么你可能想要:

I found this tutorial which explains how to do it and reasons why you might want to:

http://adam.gomaa.us/blog/2009/feb/16/subclassing-django-querysets/index.html

这篇关于在Django中,您可以向查询集中添加一个方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆