python 将属性添加到 Django 模型的 Meta 类中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1088431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:27:16  来源:igfitidea点击:

Adding attributes into Django Model's Meta class

pythondjangodjango-modelsmetadata

提问by Andrey Fedorov

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 do the definitions of these seems to be in the models themselves, a la:

我正在编写一个 mixin,它可以让我的模型很容易地转换成一个深层的值字典(有点像 .values(),但遍历关系)。对这些进行定义的最干净的地方似乎是模型本身,例如:

class Person(models.Model, DeepValues):
    name = models.CharField(blank=True, max_length=100)
    tribe = models.ForeignKey('Tribes')

    class Meta:
        schema = {
            'name' : str,
            'tribe' : {
                'name' : str
            }
        }

Person.objects.all().deep_values() => {
    'name' : 'Andrey Fedorov',
    'tribe' : {
        'name' : 'Mohicans'
    }
}

However, Django complains about my including this in class Metawith:

但是,Django 抱怨我将其包含在class Meta

TypeError: 'class Meta' got invalid attribute(s): schema

(entire stack trace here)

此处为整个堆栈跟踪)

Now, I suppose I could elaborately override this in my mixin, but is there a more elegant way of storing this information?

现在,我想我可以在我的 mixin 中精心覆盖它,但是有没有更优雅的方式来存储这些信息?

回答by Vinay Sajip

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.

显然,如果 Django 添加了它自己的“模式”属性,这将会中断。但是,嘿,这是一个想法......你总是可以选择一个不太可能发生冲突的属性名称。