1

I'm creating a django project where any user can create forms with any number of fields. For example user A could create the follow form:

  • Name of field: Field_1 - Type: Text
  • Name of field: Field_2 - Type: Date
  • Name of field: Field_3 - Type: File

And user B could create:

  • Name of field: name - Type: Text
  • Name of field: phone - Type: Text

Look that the user need to say to the program the name of the field and type. Since is a dynamic way to create any number of forms and any number of field for each forms. What would be the most efficient way to create the database model?

Take into account that the program does not know the name of the field until the user send it. So in the views, I can't process it with exact name of fields.

dfrojas
  • 673
  • 1
  • 13
  • 32

1 Answers1

1

If you create two tables in your database you can handle this pretty easily. Have one table that stores the serialized form as JSON, and another table that holds the form data (and links to the form definition).

How you serialize it is up to you but it would look something like this:

Serialized form

{
  "fields": [
    {
      "name": "field_name"
      "type": "text"
      "attrs": []
    }
  ]
}

Serialized data (ForeignKey's to above form)

{
  "data": {
    "field_name": "value"
  }
}

The advantage to doing this is you aren't creating models on the fly, and your database stays a lot cleaner because you won't have tons of tables lying around.

Jessie
  • 2,319
  • 1
  • 17
  • 32