Katsuya Obara
Katsuya Obara

Reputation: 963

How I can get attribute from queryset using prefetch_related in Django?

I have following model and extracted queryset using prefetch_related as below.

queryset = Light.objects.filter(
    certificate__name="A").prefetch_related('zone__namingzone'
)  

From this queryset, I want to get following data set.

{"naming1":lpd1,"naming2":lpd2...}  

However, when I try to extract attribute from queryset as below, I get create_reverse_many_to_one_manager

for i in queryset:
    print (i.zone.namingzone)

What I want to get is naming attribute in naming table. Could anyone tell me how I can extract this?

models.py

class Certificate(models.Model):
    name=models.CharField(max_length=20)

class Zone(models.Model):
    zone=models.CharField(max_length=20)

class Light(models.Model):
    certificate=models.ForeignKey(Certificate, on_delete=models.CASCADE,related_name='certificate')
    zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone')
    lpd=models.IntegerField()

    class Meta:
        unique_together = (('certificate', 'zone'),)

class Naming(models.Model):
    zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='namingzone')
    naming=models.CharField(max_length=20)

Upvotes: 0

Views: 690

Answers (1)

Bruno A.
Bruno A.

Reputation: 1875

When you traverse a FK in reverse, you end up with a manager, and multiple items on the other side. So i.zone.namingzone in your for loop is a manager, not a NamingZone. If you change your print loop to:

for i in queryset:
    print (i.zone.namingzone.all())

You should see all the naming zones for your item. You can extract the naming field from each NamingZone from the queryset as follows:

 queryset.values('zone__namingzone__naming')

You probably want to extract a few other fields from your Light model, like the lpd for instance:

 queryset.values('lpd', 'zone__namingzone__naming')

You might have a same ldp several times, as many times as it has naming zones.

Upvotes: 2

Related Questions