If I have a custom object manager with a custom create
function for a model:
class CustomManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(custom=True)
def create(self):
kwargs["custom"] = True
return super().create(**kwargs)
class Item(models.Model):
customs = CustomManager()
custom = BooleanField()
...
And I use that custom manager as the queryset for a view:
class ItemViewSet(views.ModelViewSet):
queryset = Item.customs.all()
Will the ItemViewSet
's create/post function automatically apply my custom object manager's kwargs["custom"] = True
?
The creation on ModelViewSet
s is handled by the serializer_class
as seen on the CreateModelMixin
and same thing for the update - a serializer.save()
is called.
Assuming you're using a straightforward ModelSerializer
, this is what gets called on a serializer.save()
that does the creation of an object:
instance = ModelClass._default_manager.create(**validated_data)
So it will use the _default_manager
of your model, which, according to the docs, will be the first manager declared on the class - so in theory it should be your custom manager.
Btw, I strongly recommend going through DRF's code whenever you find yourself in situations like these. The code is really straightforward and accessible. There are websites like Classy Django REST Framework
that can make it even easier to navigate around the code.