开发者

How Django QuerySet initialization works?

开发者 https://www.devze.com 2023-02-06 13:11 出处:网络
I\'m referring to the code snippet in the first answer taken from this post: Custom QuerySet and Manager without breaking DRY?

I'm referring to the code snippet in the first answer taken from this post: Custom QuerySet and Manager without breaking DRY?

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:
                return getattr(self.get_query_set(), attr, *args)

        def get_query_set(self):
            return self.model.QuerySet(self.model)

Here is the model:

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):
            se开发者_运维百科lf.filter(account = account, deleted=False, *args, **kwargs)

self.model.QuerySet(self.model) always receives a same model, but the result QuerySet depends on the input QuerySet. For example:

Inquiry.objects.all()[:5].active_for_account(xyz), then active_for_account will receive a query set of 5 items, while in Inquiry.objects.all()[:7].active_for_account(xyz), active_for_account will receive a query set of 7 items. Here are stack traces:

Inquiry.objects.all()[:5].active_for_account(xyz) 
    return getattr(self.get_query_set(), attr, *args),
       return self.model.QuerySet(self.model)   (1)

Inquiry.objects.all()[:7].active_for_account(xyz) 
    return getattr(self.get_query_set(), attr, *args),
       return self.model.QuerySet(self.model)   (2)

Why are results at (1) and (2) different?


I'm not entirely sure what you're asking here.

Inquiry.objects.all()[:5] doesn't give you give objects, it gives you a single QuerySet object which contains five elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消