[Answered ]-Display some field from two tables django orm

2👍

There are two options-

1) Since you are using ForeignKey, there may be multiple Trpinangsuran objects for each Trpinjaman object, hence you’ll have to decide which one of those multiple objects to use. One way is taking the first Trpinangsuran object for each Trpinjaman object. You can do following-

datapinjam=Trpinjaman.objects.all()
for obj in datapinjam:
    obj.uid,
    obj.cjenispinjaman,
    trpinangsuran_obj = obj.trpinangsuran_set.first()
    trpinangsuran_obj.cbulan,
    trpinangsuran_obj.ccicilanke,

— You can also use order_by (docs) to decide on what basis you want to take the first.

2) If you are sure there will always be one Trpinangsuran object for each Trpinjaman object, I’ll recommend using OneToOneField instead of ForeignKey. Then it’ll be something like this-

datapinjam=Trpinjaman.objects.all()
for obj in datapinjam:
    obj.uid,
    obj.cjenispinjaman,
    obj.trpinangsuran.cbulan,
    obj.trpinangsuran.ccicilanke,

Hope it helps, also please go through django queryset docs.

0👍

cbulan is part of the Trpinangsuran model. By doing:

datapinjam=Trpinjaman.objects.all()

you only get objects of the Trpinjaman type whose only fields are uid and cjenispinjaman.

To show all elements of both models you need to do a loop over all elements of Trpinangsuran and all elements of Trpinjaman

👤fmdra

Leave a comment