Skip to main content
 首页 » 编程设计

python之如何在 Django 中创建用户定义的字段

2024年09月03日37qlqwjy

好的,我正在开发一个具有多个不同模型的 Django 应用程序,即帐户、联系人等,每个模型都有一组不同的字段。除了现有字段之外,我需要能够允许我的每个用户定义他们自己的字段。我见过几种不同的实现方式,从拥有大量 CustomFields 到将自定义名称映射到每个用户使用的每个字段。我似乎也有关于实现用户定义字段的复杂映射或 XML/JSON 样式存储/检索的建议。

所以我的问题是,有人在 Django 应用程序中实现了用户定义的字段吗?如果是,您是如何做到的以及您在整体实现(稳定性、性能等)方面的经验如何?

更新:我的目标是允许我的每个用户为每种记录类型(帐户、联系人等)创建 n 个并将用户定义的数据与每个记录相关联。因此,例如,我的一个用户可能想要将 SSN 与他的每个联系人相关联,因此我需要为他创建的每个联系人记录存储该附加字段。

谢谢!

标记

请您参考如下方法:

如果您要使用外键怎么办?

此代码(未经测试且用于演示)假设存在一组系统范围的自定义字段。要使其特定于用户,您需要将“user = models.ForiegnKey(User)”添加到 CustomField 类中。

class Account(models.Model): 
    name = models.CharField(max_length=75) 
 
    # ... 
 
    def get_custom_fields(self): 
        return CustomField.objects.filter(content_type=ContentType.objects.get_for_model(Account)) 
    custom_fields = property(get_fields) 
 
class CustomField(models.Model): 
    """ 
    A field abstract -- it describe what the field is.  There are one of these 
    for each custom field the user configures. 
    """ 
    name = models.CharField(max_length=75) 
    content_type = models.ForeignKey(ContentType) 
 
class CustomFieldValueManager(models.Manager): 
 
    get_value_for_model_instance(self, model): 
        content_type = ContentType.objects.get_for_model(model) 
        return self.filter(model__content_type=content_type, model__object_id=model.pk) 
 
 
class CustomFieldValue(models.Model): 
    """ 
    A field instance -- contains the actual data.  There are many of these, for 
    each value that corresponds to a CustomField for a given model. 
    """ 
    field = models.ForeignKey(CustomField, related_name='instance') 
    value = models.CharField(max_length=255) 
    model = models.GenericForeignKey() 
 
    objects = CustomFieldValueManager() 
 
# If you wanted to enumerate the custom fields and their values, it would look 
# look like so: 
 
account = Account.objects.get(pk=1) 
for field in account.custom_fields: 
    print field.name, field.instance.objects.get_value_for_model_instance(account)