Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Django's RelatedManager methods

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.

like image 530
brildum Avatar asked Jan 14 '11 18:01

brildum


1 Answers

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.

like image 184
Daniel Roseman Avatar answered Nov 12 '22 01:11

Daniel Roseman