Iterate over Queryset backwards with Foreign Keys

Question:

I am trying to iterate over a queryset for a certain model and want to go over a table to another table. My models are the following (shrinked to a smaller version):

class Erp(models.Model):
    erp_id = models.AutoField(primary_key=True)
    target_item = models.ForeignKey('Items', models.DO_NOTHING,related_name='target_item')

class PE(models.Model):
    pe_id = models.AutoField(primary_key=True)
    item = models.ForeignKey(Items, models.DO_NOTHING, related_name='pe_item')

class Items(models.Model):
    item_id = models.AutoField(primary_key=True)
    item_name = models.Charfield(max_length=20)

My Queryset looks like this where I am trying to loop through and want to print stuff for the class Erp:

pe_queryset = PE.objects.filter(item_id=2)
for pe in pe_queryset:
    print(pe.item.item_name) # is working
    print(pe.item.target_item.erp_id) # is not working
    print(pe.item.target_item) # gives back Erp.None

Is it possible to iterate through the entry to another tables Foreign Key like this or how could I accomplish to get the value from ERP with my Queryset?

I tried to iterate through every possible column name.

pe_queryset = PE.objects.filter(item_id=2)
for pe in pe_queryset:
    print(pe.item.item_name) # is working
    print(pe.item.target_item.erp_id) # is not working
    print(pe.item.target_item) # gives back Erp.None

Asked By: Will Heeme

||

Answers:

Erp is not a single object instance like item so you should use its relationship as described in the docs to retrieve related data. Here is an example:

pe_qs = PE.objects.filter(item_id=2)

for pe_obj in pe_qs:
    print(pe_obj.item.item_name)
    # You can use .values to obtain id's
    print(pe_obj.item.target_item.all().values('erp_id'))

    # Or Iterate directly
    erp_qs = pe_obj.item.target_item.all()
    for erp_obj in erp_qs:
        print(erp_obj.erp_id)
Answered By: Niko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.