简体   繁体   中英

join two tables in django ORM using foreign key

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?

I still can't completely understand this question. But with 2 model linked with .OneToOneField, you can do it like:

pos = Position3.objects.all()
# Got all the pos (you can do filter or something else
# then with the object pos, you can get the parent_order like:
order = pos.parent_order # Or for p in pos: or = p.parent_order
# And FK make one to many relationship, OneToOne ~> same way

You're not doing anything wrong. The ticker field is in the related InternalOrder field; you can access it via new[0].parent_order.ticker .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM