是否可以动态定义模型字段的名称?

时间:2021-08-31 20:27:04

Now I have this code:

现在我有这个代码:

class Mymodel(models.Model):
    xxxx_count = ForeignCountField(filter={'foreign_table__xxxx': True})
    yyyy_count = ForeignCountField(filter={'foreign_table__yyyy': True})
    zzzz_count = ForeignCountField(filter={'foreign_table__zzzz': True})
    qqqq_count = ForeignCountField(filter={'foreign_table__qqqq': True})
    ssss_count = ForeignCountField(filter={'foreign_table__ssss': True})
    rrrr_count = ForeignCountField(filter={'foreign_table__rrrr': True})

I want something like this:

我想要这样的东西:

class Mymodel(models.Model):
    for code in ['xxxx','yyyy','zzzz','qqqq','ssss','rrrr']:
        setattr(self, '%s_count' % code, ForeignCountField(filter={'foreign_table__%s' % code: True}))

But when I try to do this, error raised: "self doesn't defined". Do I need to put this code into some other place?

但是当我尝试这样做时,错误提出:“自我没有定义”。我需要将此代码放入其他地方吗?

4 个解决方案

#1


If you want to add fields outside model definition you have to use add_to_class model method:

如果要在模型定义之外添加字段,则必须使用add_to_class模型方法:

class Mymodel(models.Model):
    pass

for code in ['xxxx','yyyy','zzzz','qqqq','ssss','rrrr']:
    Mymodel.add_to_class('%s_count' % code, ForeignCountField(filter={'foreign_table__%s' % code: True})))

#2


The way to automate the creation of multiple class attributes is by writing a metaclass. It'd certainly be possible to subclass Django's ModelBase metaclass and add the functionality you need; but it would also be overkill and probably less maintainable than just writing them out.

自动创建多个类属性的方法是编写元类。当然可以继承Django的ModelBase元类并添加你需要的功能;但它也可能过度杀伤,而且可能不如仅仅写出来那么可维护。

#3


I'd like to know a bit more about the design decisions that got you to this point. What is a ForeignCountField and why do you need it? Shouldn't it be a property of the respective tables? (a method on the manager or a classmethod?)

我想更多地了解那些让你到目前为止的设计决策。什么是ForeignCountField,为什么需要它?它不应该是各自表的属性吗? (经理或类方法的方法?)

#4


Maybe you need to put you're code in the constructor method init of your class.

也许你需要把你的代码放在你的类的构造函数方法init中。

def __init__(self, *args, **kwargs):
    .....
    super(MyModel, self).__init__(*args, **kwargs)

Edit: Sorry this don't work. Maybe you can try looking at This, 'this works with django 0.96. There are some modification that make it hard to adjust it with django version 1.0'.

编辑:对不起,这不起作用。也许你可以尝试看看这个,'这适用于django 0.96。有一些修改使得用django版本1.0'很难调整它。

if you wan't it Dirty and Quick you can try something like this:

如果你不喜欢Dirty and Quick你可以尝试这样的事情:

class Foo(models.Model):
    letters = ["A", "B", "C"]
    for l in letters:
        exec "%s_count = models.CharField(max_length=255)" % l

#1


If you want to add fields outside model definition you have to use add_to_class model method:

如果要在模型定义之外添加字段,则必须使用add_to_class模型方法:

class Mymodel(models.Model):
    pass

for code in ['xxxx','yyyy','zzzz','qqqq','ssss','rrrr']:
    Mymodel.add_to_class('%s_count' % code, ForeignCountField(filter={'foreign_table__%s' % code: True})))

#2


The way to automate the creation of multiple class attributes is by writing a metaclass. It'd certainly be possible to subclass Django's ModelBase metaclass and add the functionality you need; but it would also be overkill and probably less maintainable than just writing them out.

自动创建多个类属性的方法是编写元类。当然可以继承Django的ModelBase元类并添加你需要的功能;但它也可能过度杀伤,而且可能不如仅仅写出来那么可维护。

#3


I'd like to know a bit more about the design decisions that got you to this point. What is a ForeignCountField and why do you need it? Shouldn't it be a property of the respective tables? (a method on the manager or a classmethod?)

我想更多地了解那些让你到目前为止的设计决策。什么是ForeignCountField,为什么需要它?它不应该是各自表的属性吗? (经理或类方法的方法?)

#4


Maybe you need to put you're code in the constructor method init of your class.

也许你需要把你的代码放在你的类的构造函数方法init中。

def __init__(self, *args, **kwargs):
    .....
    super(MyModel, self).__init__(*args, **kwargs)

Edit: Sorry this don't work. Maybe you can try looking at This, 'this works with django 0.96. There are some modification that make it hard to adjust it with django version 1.0'.

编辑:对不起,这不起作用。也许你可以尝试看看这个,'这适用于django 0.96。有一些修改使得用django版本1.0'很难调整它。

if you wan't it Dirty and Quick you can try something like this:

如果你不喜欢Dirty and Quick你可以尝试这样的事情:

class Foo(models.Model):
    letters = ["A", "B", "C"]
    for l in letters:
        exec "%s_count = models.CharField(max_length=255)" % l