自定义查询集和管理器而不破坏 DRY?

发布于 2024-08-19 10:56:44 字数 1257 浏览 12 评论 0原文

我正在尝试找到一种方法来实现自定义 QuerySet 和自定义 Manager 而不破坏 DRY。这就是我到目前为止所拥有的:

class MyInquiryManager(models.Manager):
    def for_user(self, user):
        return self.get_query_set().filter(
                    Q(assigned_to_user=user) |
                    Q(assigned_to_group__in=user.groups.all())
                )

class Inquiry(models.Model):   
    ts = models.DateTimeField(auto_now_add=True)
    status = models.ForeignKey(InquiryStatus)
    assigned_to_user = models.ForeignKey(User, blank=True, null=True)
    assigned_to_group = models.ForeignKey(Group, blank=True, null=True)
    objects = MyInquiryManager()

这工作得很好,直到我做了这样的事情:

inquiries = Inquiry.objects.filter(status=some_status)
my_inquiry_count = inquiries.for_user(request.user).count()

这会立即破坏一切,因为 QuerySet 没有与 Manager 相同的方法。我尝试创建一个自定义 QuerySet 类,并在 MyInquiryManager 中实现它,但最终复制了所有方法定义。

我还发现 这个片段 有效,但我需要将额外的参数传递给for_user,因此它会崩溃,因为它严重依赖于重新定义get_query_set

有没有一种方法可以做到这一点,而无需重新定义 QuerySet 和 Manager 子类中的所有方法?

I'm trying to find a way to implement both a custom QuerySet and a custom Manager without breaking DRY. This is what I have so far:

class MyInquiryManager(models.Manager):
    def for_user(self, user):
        return self.get_query_set().filter(
                    Q(assigned_to_user=user) |
                    Q(assigned_to_group__in=user.groups.all())
                )

class Inquiry(models.Model):   
    ts = models.DateTimeField(auto_now_add=True)
    status = models.ForeignKey(InquiryStatus)
    assigned_to_user = models.ForeignKey(User, blank=True, null=True)
    assigned_to_group = models.ForeignKey(Group, blank=True, null=True)
    objects = MyInquiryManager()

This works fine, until I do something like this:

inquiries = Inquiry.objects.filter(status=some_status)
my_inquiry_count = inquiries.for_user(request.user).count()

This promptly breaks everything because the QuerySet doesn't have the same methods as the Manager. I've tried creating a custom QuerySet class, and implementing it in MyInquiryManager, but I end up replicating all of my method definitions.

I also found this snippet which works, but I need to pass in the extra argument to for_user so it breaks down because it relies heavily on redefining get_query_set.

Is there a way to do this without redefining all of my methods in both the QuerySet and the Manager subclasses?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

如果没有你 2024-08-26 10:56:44

Django 1.7 发布了一种新且简单的方法来创建组合查询集和模型管理器:

class InquiryQuerySet(models.QuerySet):
    def for_user(self, user):
        return self.filter(
            Q(assigned_to_user=user) |
            Q(assigned_to_group__in=user.groups.all())
        )

class Inquiry(models.Model):
    objects = InqueryQuerySet.as_manager()

请参阅使用 QuerySet 方法创建管理器了解更多详细信息。

The Django 1.7 released a new and simple way to create combined queryset and model manager:

class InquiryQuerySet(models.QuerySet):
    def for_user(self, user):
        return self.filter(
            Q(assigned_to_user=user) |
            Q(assigned_to_group__in=user.groups.all())
        )

class Inquiry(models.Model):
    objects = InqueryQuerySet.as_manager()

See Creating Manager with QuerySet methods for more details.

踏月而来 2024-08-26 10:56:44

Django 已更改! 在使用此答案(写于 2009 年)中的代码之前,请务必查看其余答案和 Django 文档,看看是否有更合适的解决方案。


我实现这一点的方法是添加实际的 get_active_for_account 作为自定义 QuerySet 的方法。然后,为了使其在管理器之外工作,您可以简单地捕获 __getattr__ 并相应地返回它。

为了使该模式可重用,我提取了 Manager 位到单独的模型管理器:

custom_queryset/models.py

from django.db import models
from django.db.models.query import QuerySet

class CustomQuerySetManager(models.Manager):
    """A re-usable Manager to access a custom QuerySet"""
    def __getattr__(self, attr, *args):
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            # don't delegate internal methods to the queryset
            if attr.startswith('__') and attr.endswith('__'):
                raise
            return getattr(self.get_query_set(), attr, *args)

    def get_query_set(self):
        return self.model.QuerySet(self.model, using=self._db)

一旦你得到了它,在你的模型上你需要做的就是定义一个QuerySet作为自定义内部类和将管理器设置为您的自定义管理器:

your_app/models.py

from custom_queryset.models import CustomQuerySetManager
from django.db.models.query import QuerySet

class Inquiry(models.Model):
    objects = CustomQuerySetManager()

    class QuerySet(QuerySet):
        def active_for_account(self, account, *args, **kwargs):
            return self.filter(account=account, deleted=False, *args, **kwargs)

使用此模式,以下任何一个都可以工作:

>>> Inquiry.objects.active_for_account(user)
>>> Inquiry.objects.all().active_for_account(user)
>>> Inquiry.objects.filter(first_name='John').active_for_account(user)

UPD 如果您将其与自定义用户 (AbstractUser) 一起使用,你需要改变

class CustomQuerySetManager(models.Manager):

from django.contrib.auth.models import UserManager

class CustomQuerySetManager(UserManager):
    ***

Django has changed! Before using the code in this answer, which was written in 2009, be sure to check out the rest of the answers and the Django documentation to see if there is a more appropriate solution.


The way I've implemented this is by adding the actual get_active_for_account as a method of a custom QuerySet. Then, to make it work off the manager, you can simply trap the __getattr__ and return it accordingly

To make this pattern re-usable, I've extracted out the Manager bits to a separate model manager:

custom_queryset/models.py

from django.db import models
from django.db.models.query import QuerySet

class CustomQuerySetManager(models.Manager):
    """A re-usable Manager to access a custom QuerySet"""
    def __getattr__(self, attr, *args):
        try:
            return getattr(self.__class__, attr, *args)
        except AttributeError:
            # don't delegate internal methods to the queryset
            if attr.startswith('__') and attr.endswith('__'):
                raise
            return getattr(self.get_query_set(), attr, *args)

    def get_query_set(self):
        return self.model.QuerySet(self.model, using=self._db)

Once you've got that, on your models all you need to do is define a QuerySet as a custom inner class and set the manager to your custom manager:

your_app/models.py

from custom_queryset.models import CustomQuerySetManager
from django.db.models.query import QuerySet

class Inquiry(models.Model):
    objects = CustomQuerySetManager()

    class QuerySet(QuerySet):
        def active_for_account(self, account, *args, **kwargs):
            return self.filter(account=account, deleted=False, *args, **kwargs)

With this pattern, any of these will work:

>>> Inquiry.objects.active_for_account(user)
>>> Inquiry.objects.all().active_for_account(user)
>>> Inquiry.objects.filter(first_name='John').active_for_account(user)

UPD if you are using it with custom user(AbstractUser), you need to change
from

class CustomQuerySetManager(models.Manager):

to

from django.contrib.auth.models import UserManager

class CustomQuerySetManager(UserManager):
    ***
忆沫 2024-08-26 10:56:44

您可以使用 mixin 在管理器和查询集上提供方法。

这也避免了使用 __getattr__() 方法。

from django.db.models.query import QuerySet

class PostMixin(object):
    def by_author(self, user):
        return self.filter(user=user)

    def published(self):
        return self.filter(published__lte=datetime.now())

class PostQuerySet(QuerySet, PostMixin):
    pass

class PostManager(models.Manager, PostMixin):
    def get_query_set(self):
        return PostQuerySet(self.model, using=self._db)

You can provide the methods on the manager and queryset using a mixin.

This also avoids the use of a __getattr__() approach.

from django.db.models.query import QuerySet

class PostMixin(object):
    def by_author(self, user):
        return self.filter(user=user)

    def published(self):
        return self.filter(published__lte=datetime.now())

class PostQuerySet(QuerySet, PostMixin):
    pass

class PostManager(models.Manager, PostMixin):
    def get_query_set(self):
        return PostQuerySet(self.model, using=self._db)
等待圉鍢 2024-08-26 10:56:44

您现在可以使用 from_queryset() 方法您的经理更改其基本查询集。

定义一次查询集方法和管理器方法

这允许您从文档中

对于高级用法,您可能需要自定义管理器和自定义查询集。您可以通过调用 Manager.from_queryset() 来完成此操作,该方法返回基 Manager 的子类以及自定义 QuerySet 方法的副本:

class InqueryQueryset(models.Queryset):
    def custom_method(self):
        """ available on all default querysets"""

class BaseMyInquiryManager(models.Manager):
    def for_user(self, user):
        return self.get_query_set().filter(
                    Q(assigned_to_user=user) |
                    Q(assigned_to_group__in=user.groups.all())
                )

MyInquiryManager = BaseInquiryManager.from_queryset(InquiryQueryset)

class Inquiry(models.Model):   
    ts = models.DateTimeField(auto_now_add=True)
    status = models.ForeignKey(InquiryStatus)
    assigned_to_user = models.ForeignKey(User, blank=True, null=True)
    assigned_to_group = models.ForeignKey(Group, blank=True, null=True)
    objects = MyInquiryManager()

You can now use the from_queryset() method on you manager to change its base Queryset.

This allows you to define your Queryset methods and your manager methods only once

from the docs

For advanced usage you might want both a custom Manager and a custom QuerySet. You can do that by calling Manager.from_queryset() which returns a subclass of your base Manager with a copy of the custom QuerySet methods:

class InqueryQueryset(models.Queryset):
    def custom_method(self):
        """ available on all default querysets"""

class BaseMyInquiryManager(models.Manager):
    def for_user(self, user):
        return self.get_query_set().filter(
                    Q(assigned_to_user=user) |
                    Q(assigned_to_group__in=user.groups.all())
                )

MyInquiryManager = BaseInquiryManager.from_queryset(InquiryQueryset)

class Inquiry(models.Model):   
    ts = models.DateTimeField(auto_now_add=True)
    status = models.ForeignKey(InquiryStatus)
    assigned_to_user = models.ForeignKey(User, blank=True, null=True)
    assigned_to_group = models.ForeignKey(Group, blank=True, null=True)
    objects = MyInquiryManager()
不喜欢何必死缠烂打 2024-08-26 10:56:44

基于django 3.1.3源代码,我找到了一个简单的解决方案

from django.db.models.manager import BaseManager

class MyQuerySet(models.query.QuerySet):
      def my_custom_query(self):
          return self.filter(...)

class MyManager(BaseManager.from_queryset(MyQuerySet)):
     ...

class MyModel(models.Model):
     objects = MyManager()

based on django 3.1.3 source code, i found a simple solution

from django.db.models.manager import BaseManager

class MyQuerySet(models.query.QuerySet):
      def my_custom_query(self):
          return self.filter(...)

class MyManager(BaseManager.from_queryset(MyQuerySet)):
     ...

class MyModel(models.Model):
     objects = MyManager()
熟人话多 2024-08-26 10:56:44

T. Stone 方法的略微改进版本:

def objects_extra(mixin_class):
    class MixinManager(models.Manager, mixin_class):
        class MixinQuerySet(QuerySet, mixin_class):
            pass

        def get_query_set(self):
            return self.MixinQuerySet(self.model, using=self._db)

    return MixinManager()

类装饰器使使用变得简单如下:

class SomeModel(models.Model):
    ...
    @objects_extra
    class objects:
        def filter_by_something_complex(self, whatever parameters):
            return self.extra(...)
        ...

更新:支持非标准 Manager 和 QuerySet 基类,例如 @objects_extra(django.contrib.gis.db.models.GeoManager, django.contrib.gis .db.models.query.GeoQuerySet):

def objects_extra(Manager=django.db.models.Manager, QuerySet=django.db.models.query.QuerySet):
    def oe_inner(Mixin, Manager=django.db.models.Manager, QuerySet=django.db.models.query.QuerySet):
        class MixinManager(Manager, Mixin):
            class MixinQuerySet(QuerySet, Mixin):
                pass

            def get_query_set(self):
                return self.MixinQuerySet(self.model, using=self._db)

        return MixinManager()

    if issubclass(Manager, django.db.models.Manager):
        return lambda Mixin: oe_inner(Mixin, Manager, QuerySet)
    else:
        return oe_inner(Mixin=Manager)

A slightly improved version of T. Stone’s approach:

def objects_extra(mixin_class):
    class MixinManager(models.Manager, mixin_class):
        class MixinQuerySet(QuerySet, mixin_class):
            pass

        def get_query_set(self):
            return self.MixinQuerySet(self.model, using=self._db)

    return MixinManager()

Class decorators make usage as simple as:

class SomeModel(models.Model):
    ...
    @objects_extra
    class objects:
        def filter_by_something_complex(self, whatever parameters):
            return self.extra(...)
        ...

Update: support for nonstandard Manager and QuerySet base classes, e. g. @objects_extra(django.contrib.gis.db.models.GeoManager, django.contrib.gis.db.models.query.GeoQuerySet):

def objects_extra(Manager=django.db.models.Manager, QuerySet=django.db.models.query.QuerySet):
    def oe_inner(Mixin, Manager=django.db.models.Manager, QuerySet=django.db.models.query.QuerySet):
        class MixinManager(Manager, Mixin):
            class MixinQuerySet(QuerySet, Mixin):
                pass

            def get_query_set(self):
                return self.MixinQuerySet(self.model, using=self._db)

        return MixinManager()

    if issubclass(Manager, django.db.models.Manager):
        return lambda Mixin: oe_inner(Mixin, Manager, QuerySet)
    else:
        return oe_inner(Mixin=Manager)
眼眸 2024-08-26 10:56:44

在某些用例中,我们需要 从管理器调用自定义 QuerySet 方法,而不是使用 QuerySet 的 get_manager 方法。

根据已接受的解决方案评论之一中发布的解决方案,混合就足够了。

class CustomQuerySetManagerMixin:
    """
    Allow Manager which uses custom queryset to access queryset methods directly.
    """
    def __getattr__(self, name):
        # don't delegate internal methods to queryset
        # NOTE: without this, Manager._copy_to_model will end up calling
        # __getstate__ on the *queryset* which causes the qs (as `all()`)
        #  to evaluate itself as if it was being pickled (`len(self)`)
        if name.startswith('__'):
            raise AttributeError
        return getattr(self.get_queryset(), name)

例如,

class BookQuerySet(models.QuerySet):
    def published(self):
        return self.filter(published=True)

    def fiction(self):
        return self.filter(genre="fiction")

    def non_fiction(self):
        return self.filter(genre="non-fiction")

class BookManager(CustomQuerySetManagerMixin, models.Manager):
    def get_queryset(self):
        return BookQuerySet(self.model, using=self._db).published()

class Book(models.Model):
    title = models.CharField(max_length=200)
    genre = models.CharField(choices=[('fiction', _('Fiction')), ('non-fiction', _('Non-Fiction'))])
    published = models.BooleanField(default=False)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")

    objects = BookManager()

class Author(models.Model):
    name = models.CharField(max_length=200)

通过上面的内容,我们可以像下面一样访问相关对象(Book),而无需在管理器中为每个查询集方法定义新方法。

fiction_books = author.books.fiction()

There are use-cases where we need to call custom QuerySet methods from the manager instead of using the get_manager method of a QuerySet.

A mixin would suffice based on the solution posted in one of the accepted solution comments.

class CustomQuerySetManagerMixin:
    """
    Allow Manager which uses custom queryset to access queryset methods directly.
    """
    def __getattr__(self, name):
        # don't delegate internal methods to queryset
        # NOTE: without this, Manager._copy_to_model will end up calling
        # __getstate__ on the *queryset* which causes the qs (as `all()`)
        #  to evaluate itself as if it was being pickled (`len(self)`)
        if name.startswith('__'):
            raise AttributeError
        return getattr(self.get_queryset(), name)

For example,

class BookQuerySet(models.QuerySet):
    def published(self):
        return self.filter(published=True)

    def fiction(self):
        return self.filter(genre="fiction")

    def non_fiction(self):
        return self.filter(genre="non-fiction")

class BookManager(CustomQuerySetManagerMixin, models.Manager):
    def get_queryset(self):
        return BookQuerySet(self.model, using=self._db).published()

class Book(models.Model):
    title = models.CharField(max_length=200)
    genre = models.CharField(choices=[('fiction', _('Fiction')), ('non-fiction', _('Non-Fiction'))])
    published = models.BooleanField(default=False)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")

    objects = BookManager()

class Author(models.Model):
    name = models.CharField(max_length=200)

With the above, we can access related objects (Book) like below without defining new methods in the manager for each queryset method.

fiction_books = author.books.fiction()
×眷恋的温暖 2024-08-26 10:56:44

以下内容对我有用。

def get_active_for_account(self,account,*args,**kwargs):
    """Returns a queryset that is 
    Not deleted
    For the specified account
    """
    return self.filter(account = account,deleted=False,*args,**kwargs)

这是默认管理器上的;所以我曾经做过类似的事情:

Model.objects.get_active_for_account(account).filter()

但是没有理由它不适合二级经理。

The following works for me.

def get_active_for_account(self,account,*args,**kwargs):
    """Returns a queryset that is 
    Not deleted
    For the specified account
    """
    return self.filter(account = account,deleted=False,*args,**kwargs)

This is on the default manager; so I used to do something like:

Model.objects.get_active_for_account(account).filter()

But there is no reason it should not work for a secondary manager.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文