【问题标题】:How to create user defined fields in Django如何在 Django 中创建用户定义的字段
【发布时间】:2010-11-30 14:22:22
【问题描述】:

好的,我正在开发一个 Django 应用程序,它有几个不同的模型,即 Accounts、Contacts 等,每个模型都有一组不同的字段。我需要能够允许我的每个用户在现有字段之外定义自己的字段。我已经看到了几种不同的方法来实现这一点,从拥有大量的自定义字段到将自定义名称映射到每个用户使用的每个字段。我似乎也建议实现复杂的映射或 XML/JSON 样式的存储/检索用户定义的字段。

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

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

谢谢!

标记

【问题讨论】:

  • 您可能希望明确您的目标。您是想简单地将任意元数据与这些用户相关联,还是需要按特定字段查找用户?
  • 您可能正在寻找此参考:stackoverflow.com/a/7934577/497056

标签: python django configuration modeling


【解决方案1】:

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

此代码(未经测试且用于演示)假设存在一组系统范围的自定义字段。为了使其特定于用户,您需要将“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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 2011-01-13
    • 2015-02-16
    • 2014-04-30
    相关资源
    最近更新 更多