12๐
โ
You can use a combination of a Manager
and a QuerySet
to achieve this, like so:
# model_managers.py
class CustomManager(models.Manager):
""" Enables changing the default queryset function. """
def get_queryset(self):
# Here you can change the default queryset function
return super(CustomManager, self).get_queryset(example_field=True)
class CustomQuerySet(models.QuerySet):
""" Include additional queryset functions. """
def example_filter(self):
return self.filter(other_field=False)
# models.py
class YourModel(models.Model):
# Override the default manager
objects = CustomManager.from_queryset(CustomQuerySet)() # The pair of empty parenthesis is required!
And then you can use it anywhere like:
# Will filter `example_field`
YourModel.objects.all()
# Will filter `example_field` and `other_field`
YourModel.objects.example_filter()
๐คdurdenk
1๐
You should show what you tried that didnโt work.
But nevertheless, you just need to use that call to define your own manager in the model:
class MyModel(models.Model):
...
objects = MyQuerySet.as_manager()
๐คDaniel Roseman
0๐
You can create manage class by inheriting models.Manager and then you can define your own query set method.
in model.py, we should assign class as property as given below:
example = ExampleManager()
Now we can use example instead of objects and can call respective ExampleManager method.
๐คKapil
- How can I schedule a Task to execute at a specific time using celery?
- How to create an alias for Django Model field?
Source:stackexchange.com