[Answer]-Django, extra argument for model field definition

1👍

This could break if they ever add an extra argument to a field. And monkeypatches are discouraged in general. You could go a safer route by adding a method to the Field base class:

def set_extra(self, **kwargs):
    self.extra = kwargs
    return self
models.Field.set_extra = set_extra

Then define your models like this:

class Poll(models.Model):
    question = models.CharField(max_length=200).set_extra(
            widget='xw', admin_list_order=3)

has_key is considered unpythonic, preferred way to check for key presence is:

if 'extra' in kwargs:
    self.extra = kwargs.pop('extra')

More pythonic would be just trying it and catching failure:

try:
    self.extra = kwargs.pop('extra')
except KeyError:
    pass

Leave a comment