how to override the verbose name of a superclass model field in django

后端 未结 5 1526
梦如初夏
梦如初夏 2020-12-05 02:35

Let\'s say that I have a model Foo that inherits from SuperFoo:

class SuperFoo(models.Model):
    name = models.CharField(\'name of SuperFoo instance\', max_         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 03:05

    Bearing in mind the caveat that modifying Foo._meta.fields will affect the superclass too - and therefore is only really useful if the superclass is abstract, I've wrapped the answer @Gerry gave up as a reusable class decorator:

    def modify_fields(**kwargs):
        def wrap(cls):
            for field, prop_dict in kwargs.items():
                for prop, val in prop_dict.items():
                    setattr(cls._meta.get_field(field), prop, val)
            return cls
        return wrap
    

    Use it like this:

    @modify_fields(timestamp={
        'verbose_name': 'Available From',
        'help_text': 'Earliest date you can book this'})
    class Purchase(BaseOrderItem):
        pass
    

    The example above changes the verbose_name and help_text for the inherited field 'timestamp'. You can pass in as many keyword args as there are fields you want to modify.

提交回复
热议问题