'Django prefetch_related
I have a relational model set that has 5 tables each with a one to many relationship. I'm having trouble accessing model information after the 2nd table. ex.
class TableA(models.Model):
pass
class TableB(models.Model):
tablea = models.ForeignKey(TableA, oncascade...)
class TableC(models.Model):
tableb = models.ForeignKey(TableB, oncas...)
class TableD(models.Model):
tablec = models.ForeignKey(TableC, ...)
class TableE(models.Model):
tabled = models.ForeignKey(TableE, ...)
In my views.py i'm using the prefetch related method on TableA:
from . models import *
data = TableA.objects.all().prefetch_related('tableb_set__tablec_set__tabled_set')
I can't seem to access information from TableC, TableD or TableE.
for a in data:
print(a.id)
for b in a.tableb_set.values():
print(b['id])
for c in b.tablec_set.values(): #This is where I get an error message stating the model doesn't have a relatedmanager
How can I access model information 2+ tables deep into the prefetch_related relationship?
Thanks in advance
Solution 1:[1]
using the .all() method on the _set accesses the info!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samsul Islam |
