简体   繁体   English

如何在Django模型中为类动态设置属性?

[英]How to dynamically set attributes to a class in models in Django?

I want to dynamically set attribute to models. 我想为模型动态设置属性。 Here is the way I did it. 这是我的方法。

# models.py
class pwr(models.Model):



    # test info
    tester = models.CharField(max_length=10)
    test_date = models.DateField(verbose_name='Test Date')
    test_summary = models.TextField(verbose_name='Test Summary')
    test_duration = models.CharField(max_length=20, verbose_name='Test Duration')


    for i in xrange(2):
        ii = str(i)



        test_result = 'test_result_' + ii
        test_com = 'test_comment_' + ii
        bug_level = 'bug_level_' + ii
        bug_id = 'bug_id_' + ii
        bug_sum = 'bug_summary_' + ii
        exec (test_result + "= models.CharField(max_length=20, verbose_name='Result', \
        choices=(\
        ('Pass', 'P'), \
        ('Fail', 'F'), \
        ('Not Test', 'N/T'), \
        ('Not Avaliable', 'N/A'), \
        ('Reference', 'Ref'), \
        ('Warn', 'W')\
        ))")
        exec (test_com + "= models.CharField(max_length=100,  verbose_name='Comment',  blank=True)")
        exec (bug_level + "= models.CharField(max_length=100,  verbose_name='Bug Level',  blank=True, \
                            choices=(('1', '1:Blocker'), \
                            ('2', '2:Critical'), \
                            ('3', '3:Major'), \
                            ('4', '4:Normal'), \
                            ('5', '5:Enhancement')))")
        exec (bug_id + "= models.CharField(max_length=10,  verbose_name='Bug ID',  blank=True)")
        exec (bug_sum + "= models.CharField(max_length=100,  verbose_name='Bug Summary',  blank=True)")

# When I tried to use setattr here, no 'test_attribute' field is added to table pwr in database        
setattr(pwr, 'test_attribute', models.CharField(max_length=10,  verbose_name='test attr',  blank=True))    

This seems really ugly.. Do you have any better solution for this? 这看起来确实很丑。.您对此有更好的解决方案吗? Thanks!!! 谢谢!!!

You cannot set it dynamically with setattr because you are dealing with Python descriptors , not attributes. 您不能使用setattr动态设置它,因为您正在处理Python 描述符 ,而不是属性。 This is because of the order of events when the module is imported and Python class ans descriptors put together. 这是因为导入模块并将Python类ans描述符放在一起时的事件顺序。

Naturally, you can still do this in superious dynamic language like Python. 当然,您仍然可以使用像Python这样的超级动态语言来执行此操作。 But the solution for the problem needs different approach 但是解决问题需要不同的方法

  • You can use Python metaclasses and override __new__ 您可以使用Python 元类并覆盖__new__

  • See declared_ attr in SQLAlchemy, its own way to solve this special case 请参阅SQLAlchemy中的declared_ attr,以其自身的方式解决这种特殊情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM