[Answer]-Attach mixin to model when it is created based on a field?

1👍

You can do this by defining a field subclass with a contribute_to_class method. That’s how fields with the choices attribute define a get_FOO_display method on their models.

contribute_to_class is passed the model class, and the name this field is being defined as. You can use the model class to add extra methods. It might work something like this:

class DuckField(models.CharField):

    def contribute_to_class(self, cls, name):
        super(DuckField, self).contribute_to_class(cls, name)

        # method to be added
        def quack(self):
            return '%s quacks!' % self

        # add it to the model
        cls.quack = quack

Leave a comment