对于使用关系数据库的动态属性,您可以尝试以下操作:
class Employee( models.Model ):
firstname = models.CharField( max_length=50 )
lastname = models.CharField( max_length=50 )
ssn = models.IntegerField()
class EmployeeAttribute( models.Model ):
ATTRIBUTE_CHOICES = (
(0, 'is_married'),
(1, 'spouse_name'),
(2, 'is_graduate'),
...
)
name = models.IntegerField( max_length=3, choices=ATTRIBUTE_CHOICES )
value = models.CharField( max_length=255 )
employee = models.ForeignKey( 'Employee' )
每当您想要添加一个新属性时,只需将其附加到属性选择元组中,并增加最后一个数字。
如果您的目标是不需要在每次需要添加新属性时都编写额外代码,请尝试以下操作:
class Employee( models.Model ):
firstname = models.CharField( max_length=50 )
lastname = models.CharField( max_length=50 )
ssn = models.IntegerField()
class Attribute( models.Model ):
name = models.CharField( max_length=50 )
class EmployeeAttribute( models.Model ):
attribute = models.ForeignKey( 'Attribute' )
employee = models.ForeignKey( 'Employee' )
使用这种方法,您至少可以创建一个区域,允许您通过 Django 管理员或自定义模板创建新属性。获取员工的扩展属性就像这样简单:
employee = Employee.objects.get( firstname='John', lastname='Doe' )
extended_attributes = employee.employee_attribute_set.all()