How to create custom fields in Django

Well, I am working on a Django application with several different models, namely accounts, contacts, etc., each with a different set of fields. I need each of my users to be able to define their own fields in addition to the existing fields. I saw several different ways to implement this: from a large number of CustomFields and simply matching a custom name for each field used by each user. I also provide recommendations for implementing complex mapping or storing / searching the XML / JSON style of user-defined fields.

So my question is, has anyone implemented custom fields in a Django application? If so, how did you do it and what was your experience with the overall implementation (stability, performance, etc.)?

Update. My goal is to allow each of my users to create n numbers of each type of record (accounts, contacts, etc.) and associate user-defined data with each record. For example, one of my users can associate an SSN with each of his contacts, so I will need to save this extra field for each Contact record that he creates.

Thank!

Mark

+2
source share
1 answer

What if you want to use ForeignKey?

( ) . , "user = models.ForiegnKey()" 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)
+3

All Articles