Dict as a model field

I want to add the dict field to the model, display the dict in the admin panel and be able to edit it with the administrator.

For example, I have a relationship

dict = { 'sister' : rel_score, 'mother' : rel_score, 'father': rel_score}

where rel_score (default = 0) is the score for each link. I want to save this dict in my model and display it in admin, so that I can assign these rel_score to each communication with my administrator.

Any example of how to assign ratings (priorities) for different elements and return values ​​in accordance with these assigned ratings will also be useful.

+6
source share
3 answers

It is not possible to have a DictField because the underlying database does not support this type of data structure.

You may have a RelationshipScore model for storing your relationships and a ForeignKey from it to the existing model (I will use the user as an example). eg:

 Class RelationshipScore(models.Model): user = models.ForeignKey(User) relationship = models.CharField(max_length=50, primary_key=True) score = models.IntegerField() 

Then you can add functions to the existing model to get the values:

 class User(models.Model): def get_relationship(self, rel): return RelationshipScore.objects.get(relationship=rel, user=self) def get_lowest_relationship(self): return RelationshipScore.objects.filter(user=self).order_by("-score")[0] 
+2
source

Starting with Django 1.8, postgres users can also use the HStore field .

 A field for storing mappings of strings to strings. The Python data type used is a dict. 
+1
source

Postgres user can easily use jsonfield:

 from django.db import models from django.contrib.postgres.fields import JSONField import json class Yourmodel(models.Model): name = models.CharField() dict_json = JSONField(blank=True, null=True) def __str__(self): return self.name 

and in your application:

 the_dict = {'a':1,'b':2} Yourmodel.dict_json = json.dumps(the_dict) Yourmodel.save() 

https://docs.djangoproject.com/es/1.9/ref/contrib/postgres/fields/#jsonfield

0
source

All Articles