Home > Software design >  Get the string of two upper levels in foraign relations
Get the string of two upper levels in foraign relations

Time:01-25

Good Morning,

How to get the value Entity.name about ProjectsComments row.

Top model :

class Entities(models.Model): 
    code = models.CharField(verbose_name='Código', max_length=10, blank=False, unique=True,
                                   help_text='Codigo de entidad.')
    name = models.CharField(max_length=150, verbose_name='Nombre', unique=True,
                                   help_text='Nombre de la entidad.')
    
    def __str__(self):
        return self.name

    def toJSON(self):
        item = model_to_dict(self)
        return item

Second Level:

class Projects(models.Model):
    entity = models.ForeignKey(Entities, on_delete=models.DO_NOTHING, verbose_name="Entidad")

    def __str__(self):
        return f'{self.entity}'   ' \ '   f'{self.code}'   ' \ '   f'{self.name}'  #   ' \ '   f'{self.phase}'

    def toJSON(self):
        item = model_to_dict(self)
        item['entity'] = self.entity.toJSON()
        return item
        

Third Level

class ProjectsComments(models.Model):
    project = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=0, verbose_name='Proyecto',
                                   help_text='Proyecto')


    def __str__(self):
        return f'{self.date}'   f' '   f'#'   f'{self.user}'   f'# '   f'{self.comment}'

    def toJSON(self):
        item = model_to_dict(self)
        item['project'] = self.project.toJSON()
        item['entity'] = Entities.objects.get(pk = )
        item['user'] = self.user.toJSON()
        return item

I would need that from projectscommentsListView get the value of ProjectsComments__Projects__Entity.name

I have tried get into ProjectsComments.toJSON() with :

item['entity'] = Entities.objects.get(pk = )


AND 


item['entity'] = self.entity.toJSON()

I do not know anymore.

CodePudding user response:

You can get the entity from your project since they are related

item['entity'] = self.project.entity.toJSON()

No need for another query.

  • Related