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

2 投票
1 回答
1807 浏览
提问于 2025-04-15 14:31

好的,我正在开发一个Django应用,里面有几个不同的模型,比如账户、联系人等等,每个模型都有不同的字段。我需要让每个用户除了已有的字段外,还能定义自己的字段。我见过几种实现方法,比如有很多自定义字段,然后把每个用户用的字段映射到这些自定义字段上。我也看到有人建议用复杂的映射或者用XML/JSON的方式来存储和获取用户定义的字段。

所以我想问,有没有人实现过用户定义字段的Django应用?如果有,你是怎么做的,整体实现的体验怎么样(稳定性、性能等)?

更新一下:我的目标是让每个用户可以创建任意数量的每种记录类型(账户、联系人等),并且能把用户定义的数据和每条记录关联起来。比如说,有用户可能想在每个联系人里加一个社会安全号码(SSN),那么我就需要为他创建的每个联系人记录存储这个额外的字段。

谢谢!

马克

1 个回答

4

如果你使用外键会怎么样呢?

这段代码(未经测试,仅供演示)假设有一套系统范围内的自定义字段。如果想让这些字段与特定用户相关联,你需要在CustomField类中添加一个“user = models.ForeignKey(User)”的设置。

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)

撰写回答