简体   繁体   中英

Django get_queryset method of a custom model manager has no effect on other built-in methods(get, filter, etc.)

I have created a model manager with a method that adds some string to the certain field and my goal is to apply this method every time when objects called. As I understand, this can be achieved by using the get_queryset method in the custom manager, however this only works if I call SomeModel.objects.all() . If I try to apply some filter, or get object by parametr, it simply returns me original data without my method applied.

models.py:

class BaseModelQuerySet(models.QuerySet):
    def edit_desc(self, string):
        if self.exists():
            for obj in self:
                if 'description' in obj.__dict__:
                    obj.__dict__['description'] += string
        return self


class BaseModelManager(models.Manager):
    def get_queryset(self):
        return BaseModelQuerySet(self.model, using=self._db).edit_desc('...')


class BaseModel(models.Model):
    objects = BaseModelManager()

    class Meta:
        abstract = True

Output in django shell:

>>> SomeModel.objects.all()[0].description
    'Some example of description...'
>>> SomeModel.objects.get(id=1).description
    'Some example of description'

People, what am I doing wrong, please help. Thanks thousand times in advance!

The model.objects.get method does not return a QuerySet, so the call is never handled by get_queryset . .get returns a single object, not an iterable of objects.

Therefore, you want to override the get method in your model manager to specially handle the case for .get .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM