Package: django-entangled
django-entangledEdit JSON-Model Fields using a Standard Django Form.Use-CaseA Django Model may contain fields which accept arbitrary data stored as JSON. Django itself, provides aJSON fieldto store arbitrary
serializable data.When creating a form from a model, the input field associated with a JSON field, typically is a<textarea ...></textarea>.
This textarea widget is very inpracticable for editing, because it just contains a textual representation of that
object notation. One possibility is to use a genericJSON editor,
which with some JavaScript, transforms the widget into an attribute-value-pair editor. This approach however requires
to manage the field keys ourself. It furthermore prevents us from utilizing all the nice features provided by the Django
form framework, such as field validation, normalization of data and the usage of foreign keys.By usingdjango-entangled, one can use a DjangoModelForm, and store all,
or a subset of that form fields in one or more JSON fields inside of the associated model.InstallationSimply install this Django app, for instance by invoking:pipinstalldjango-entangledThere is no need to add any configuration directives to the project'ssettings.py.ExampleSay, we have a Django model to describe a bunch of different products. The name and the price fields are common to all
products, whereas the properties can vary depending on its product type. Since we don't want to create a different
product model for each product type, we use a JSON field to store these arbitrary properties.fromdjango.dbimportmodelsclassProduct(models.Model):name=models.CharField(max_length=50)price=models.DecimalField(max_digits=5,decimal_places=2)properties=models.JSONField()In a typical form editing view, we would create a form inheriting fromModelFormand refer to this model using
themodelattribute in itsMeta-class. Then theproperties-field would show up as unstructured JSON, rendered
inside a<textarea ...></textarea>. This definitely is not what we want! Instead we create a typical Django Form using
the alternative classEntangledModelForm.fromdjango.contrib.authimportget_user_modelfromdjango.formsimportfields,modelsfromentangled.formsimportEntangledModelFormfrom.modelsimportProductclassProductForm(EntangledModelForm):color=fields.RegexField(regex=r'^#[0-9a-f]{6}$',)size=fields.ChoiceField(choices=[('s',"small"),('m',"medium"),('l',"large"),('xl',"extra large")],)tenant=models.ModelChoiceField(queryset=get_user_model().objects.filter(is_staff=True),)classMeta:model=Productentangled_fields={'properties':['color','size','tenant']}# fields provided by this formuntangled_fields=['name','price']# these fields are provided by the Product modelIn case our form inherits from anotherModelForm, rewrite the class declarartion as:classProductForm(EntangledModelFormMixin,BaseProductForm):...In addition we add a special dictionary namedentangled_fieldsto ourMeta-options. In this dictionary, the key
(here'properties') refers to the JSON-field in our modelProduct. The value (here['color', 'size', 'tenant'])
is a list of named form fields, declared in our form- or base-class of thereof. This allows us to assign all standard
Django form fields to arbitrary JSON fields declared in our Django model. Moreover, we can even use aModelChoiceFieldor aModelMultipleChoiceFieldto refer to another model object using ageneric relationSince in this form we also want to access the non-JSON fields from our Django model, we add a list nameduntangled_fieldsto ourMeta-options. In this list, (here['name', 'price']) we refer to the non-JSON fields
in our modelProduct. From both of these iterables,entangled_fieldsanduntangled_fields, the parent classEntangledModelFormthen builds theMeta-optionfields, otherwise required. Therefore you should not
usefieldsto declare this list, but rather rely onentangled_fieldsanduntangled_fields.We can use this form in any Django form view. A typical use-case, is the built-in DjangoModelAdmin:fromdjango.contribimportadminfrom.modelsimportProductfrom.formsimportProductForm@admin.register(Product)classProductAdmin(admin.ModelAdmin):form=ProductFormSince the form used by thisModelAdmin-classcan not be created dynamically,
we have to declare it explicitly using theform-attribute. This is the only change which has to be performed, in
order to store arbitrary content inside our JSON model-fields.Nested Data StructuresSometimes it can be desirable to store the data in a nested hierarchy of dictionaries, rather than having all
attribute-value-pairs in the first level of our JSON field. This can for instance be handy when merging more than one
form, all themselves ineriting fromEntangledModelFormMixin.Say that we have different types of products, all of which share the same base product form:fromdjango.contrib.authimportget_user_modelfromdjango.formsimportmodelsfromentangled.formsimportEntangledModelFormMixinfrom.modelsimportProductclassBaseProductForm(EntangledModelFormMixin):tenant=models.ModelChoiceField(queryset=get_user_model().objects.filter(is_staff=True),)classMeta:model=Productentangled_fields={'properties':['tenant']}untangled_fields=['name','price']In order to specialize our base product towards, say clothing, we typically would inherit from the base form
and add some additional fields, herecolorandsize:fromdjango.formsimportfieldsfrom.formsimportBaseProductFormfrom.modelsimportProductclassClothingProductForm(BaseProductForm):color=fields.RegexField(regex=r'^#[0-9a-f]{6}$',)size=fields.ChoiceField(choices=[('s',"small"),('m',"medium"),('l',"large"),('xl',"extra large")],)classMeta:model=Productentangled_fields={'properties':['color','size']}retangled_fields={'color':'variants.color','size':'variants.size'}By adding a name mapping from our existing field names, we can group the fieldscolorandsizeinto a sub-dictionary namedvariantsinside ourpropertiesfields. Such a field mapping is
declared through the optional Meta-optionretangled_fields. In this dictionary, all entries are
optional; if a field name is missing, it just maps to itself.This mapping table can also be used to map field names to other keys inside the resulting JSON
datastructure. This for instance is handy to map fields containg an underscore into field-names
containing instead a dash.CaveatsDue to the nature of JSON, indexing and thus building filters or sorting rules based on the fields content is not as
simple, as with standard model fields. Therefore, this approach is best suited, if the main focus is to store data,
rather than digging through data.Foreign keys are stored as"fieldname": {"model": "appname.modelname", "pk": 1234}in our JSON field, meaning that
we have no database constraints. If a target object is deleted, that foreign key points to nowhere. Therefore always
keep in mind, that we don't have any referential integrity and hence must write our code in a defensive manner.Contributing to the ProjectPlease ask question on thediscussion board.Ideas for new features shall as well be discussed on that board.Theissue trackershallexclusivelybe used to report bugs.Except for very small fixes (typos etc.), do not open a pull request without an issue.Before writing code, adopt your IDE to respect the project's.editorconfig.