1

I am new to Python/Django. I have two tables tableA

id(pk) Name desc   tableBID(fk)
1      ABC  testdesc  1
2      XYZ  testdes   2

tableB

id Name
1  firstName
2  Second Name

In Django, I have written below code

records = tableA.objects.all()

this is giving me tableA data but I need the TableB Name also.

Can anyone told me how to get the TableB name like

1      ABC  testdesc  1  firstName
2      XYZ  testdes   2  Second Name
nyi
  • 3,123
  • 4
  • 22
  • 45
vishu
  • 231
  • 1
  • 9
  • 4
    Possible duplicate of [Django: implementing JOIN using Django ORM?](https://stackoverflow.com/questions/4125379/django-implementing-join-using-django-orm) – Kamal Nayan Apr 18 '18 at 09:11

1 Answers1

4

You can use values to get required data with one query:

records = tableA.objects.values('Name', 'desc', 'tableBID__Name`)

tableBID__Name will fetch name from related TableB record.

Or to get list of objects instead of dictionaries use select_related:

records = tableA.objects.all().select_related('tableBID')
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100