Generate a dictionary from the models

1

I am working in Django and I have 5 models:

  • Company
  • Agent
  • Sensore
  • Template
  • Data

There are several relationships as fixed in code. What I want is to generate a dictionary like this example in the Views:

{
  "Empresa": {
    "Agente": {
      "Memory": [
        {
          "plantia1":"Datos",
          "plantia2":"Datos"
        },
        {
          "plantia1":"Datos",
          "plantia2":"Datos"
        }
      ]
    }
  }
}

I really do not know how to do it. This is my code:

class Empresa(models.Model):
   Name = models.CharField(null=False,blank=False, max_length=600)
   tag = models.CharField(unique=True,blank=False,null=False, max_length=60)
   def __unicode__(self):
      return self.Name

class Agente(models.Model):
    Name = models.CharField(null=False,blank=False, max_length=600)
    empresa = models.ForeignKey(Empresa)
    referencia = models.CharField(unique=True,null=False,blank=False,max_length=600)
    creado = models.DateTimeField(auto_now_add=True,blank=False)
    actualizado = models.DateTimeField(auto_now=True)
    def __unicode__(self):
       return self.Name
class Sensore(models.Model):
    Name = models.CharField(null=False,blank=False, max_length=150,unique=True)
    homepage = models.BooleanField(default=False)
    def __unicode__(self):
       return self.Name
class Plantilla(models.Model):
   Name = models.CharField(null=False,blank=False, max_length=150,unique=True)
   homepage = models.BooleanField(default=False)
   def __unicode__(self):
      return self.Name
class Dato(models.Model):
   Datos = models.CharField(null=True,blank=True, max_length=600)
   Plantillas = models.ForeignKey(Plantilla)
   Agente = models.ForeignKey(Agente)
   sensores = models.ForeignKey(Sensore)
   def agente(self):
      return self.Agente.Name
    
asked by Jamal 01.01.2019 в 18:50
source

1 answer

0

There is a module for Django called django-rest-framework that includes a package that helps serialize models and their relationships in JSON format, for example:

{
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse',
    'tracks': [
        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
        {'order': 3, 'title': 'Encore', 'duration': 159},
        ...
    ],
}

I leave a link with the documentation of the model serializers of the package that I mentioned, here is more detailed information to work with your models and the relationships they have with others.

Serializer relations

Greetings!

    
answered by 05.01.2019 в 23:19