Search code examples
pythondjangodjango-modelsdjango-viewsdjango-orm

How to get reference table fields with django model query


When I am trying to fetch foreign key table using django model I am only unable to get the referenced table details.

I have two models TblVersion and TblProject defined below

class TblVersion(models.Model):
    version_id = models.AutoField(primary_key=True)
    project = models.ForeignKey(TblProject, models.DO_NOTHING)
    version_major = models.PositiveSmallIntegerField()
    version_minor = models.PositiveSmallIntegerField()

    class Meta:
        managed = False
        db_table = 'tbl_version'


class TblProject(models.Model):
    project_id = models.AutoField(primary_key=True)
    project_name = models.CharField(max_length=32)

    class Meta:
        managed = False
        db_table = 'tbl_project'

My current code implementation:

        result= TblVersion.objects.all().select_related()
        data = serializers.serialize('json', result)
        print(data)
Code Result:
[
  {
    "model": "CCM_API.tblversion",
    "pk": 1,
    "fields": { "project": 1, "version_major": 1000, "version_minor": 0 }
  },
  {
    "model": "CCM_API.tblversion",
    "pk": 2,
    "fields": { "project": 2, "version_major": 1000, "version_minor": 0 }
  },
  {
    "model": "CCM_API.tblversion",
    "pk": 3,
    "fields": { "project": 2, "version_major": 1000, "version_minor": 2 }
  }
]


The code output lacks the foreign key fields (Project Name). I want a list of version numbers with their respective projects like this.

| Version Id | Major Version | Minor Version | Project Id | Project Name|
| -------- | -------- |-------- |-------- |-------- |
| 1   | 1000   |1 | 1| PROJ_1 |
| 2   | 1000   |1 | 2| PROJ_2 |
| 3   | 1000   |2 | 1| PROJ_1 |

Solution

  • This is the current implementation of my code that solved the problem.

    projects = []
    result = TblVersion.objects.all()    
    for ver in result:
        versions.append({
            'id':ver.version_id,
            'major_version':ver.version_major,
            'minor_version':ver.version_minor,
            'project_name':ver.project.project_id,
            'project_name':ver.project.project_name,
        })