Django's ForeignRelatedObjectsDescriptor.create_manager(...)
function dynamically creates the RelatedManager
classes and subsequently initializes an instance of the dynamically created class.
If I wanted to override the RelatedManager.add(...)
method, how would I do it?
The RelatedManager
classes are created in file: django/db/models/fields/related.py
.
An example of how I'd like to use a custom RelatedManager
is...
class Record(Model):
string = CharField()
class Managed(Model):
record = ForeignKey('Record')
boolean = BooleanField()
def view_function(...):
record = Record(string='Example')
record.save()
record.managed_set.add(Managed(boolean=True)) # How to override add()?
Any suggestions would be appreciated.
I'm not sure what you need the override for - the default queryset already does what you want.
But to answer the question, you can define a custom Manager on the model and set use_for_related_fields=True
to ensure it gets used as the automatic manager. See the documentation on controlling automatic Manager types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With