I am a beginner in Django. I am facing a problem with models which are joined through Foregin Keys.
I have two models "Internalorder2" an "Position3" as mentioned below. I want to join the tables with using Django ORM.
app/models.py
class Internalorder2(models.Model):
order_id = models.AutoField(primary_key=True)
ticker = models.CharField(max_length=64)
class Meta:
managed = True
db_table = 'internalorder2'
app/models.py
class Position3(models.Model):
pos_id = models.AutoField(primary_key=True)
parent_order = models.OneToOneField(Internalorder2, models.DO_NOTHING)
action = models.CharField(max_length=4)
class Meta:
managed = True
db_table = 'position3'
Next I have populated both the tables. After that, I run a query to extract a queryset spanning both tables using select_related function. I was expecting to see all fields of table Internalorder2 in queryset from the query. However, the queryset only contains the fields from it's own table, position3.
python manage.py shell command
from app.models.py import *
qs= Position3.objects.all().select_related("parent_order")
python shell result
In [102]: qs[0].__dict__
Out[102]:
{'_parent_order_cache': <Internalorder2: Internalorder2 object>,
'_state': <django.db.models.base.ModelState at 0x13209f0>,
'action': 'B',
'parent_order_id': 1,
'pos_id': 1}
I can access the fields from table Internalorder2 using command:
python shell result
In [112]: qs[0].parent_order.ticker
Out[112]: 'ACC'
However, this is not what I want. I want all the fields from the foregin table to added to queryset, as the queryset is fed to some other plugin as input.
Any solutions which involves making only query to database?