Adding attributes into Django Model's Meta class

后端 未结 2 372
我在风中等你
我在风中等你 2021-01-30 21:11

I\'m writing a mixin which will allow my Models to be easily translated into a deep dict of values (kind of like .values(), but traversing relationships). The cleanest place to

相关标签:
2条回答
  • 2021-01-30 21:52

    I don't know about elegant, but one pragmatic way is:

    import django.db.models.options as options
    
    options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('schema',)
    

    Obviously, this would break if Django ever added a 'schema' attribute of its own. But hey, it's a thought...you could always pick an attribute name which is less likely to clash.

    0 讨论(0)
  • 2021-01-30 22:05

    Not a direct answer, but I did not like the idea of adding it in every model where I need it to the options, so I did:

    class MyModel(models.Model):
        
        class Meta:
            ordering = ["myfield"]
    
        class MyPrefixMeta:
            my_value = "Abc"
    

    You could even put this to a abstract model and validate the set class properties in __init__ function or do things like adding a _myprefix_meta property to the model. So you had your own meta class.

    0 讨论(0)
提交回复
热议问题