[Django]-Django – How to access prefetch_related fields?

4👍

✅

Neither prefetch_related nor select_related change the way you access the related data; you do it via the fields or reverse relations, just as you would if you didn’t use those methods.

In this case, you have a queryset composed of students; each one of those will have a user attribute, which gives a User object which in turn has an applications field which gives another queryset. So, for example:

students[0].user.applications.all()[0]

1👍

While prefetch_related doesn’t change the way you access the related data, if you only care about the model at the end of the "joining chain" in a prefetch_related call, you can use QuerySet.union().

Something like this:

students = Student.objects.prefetch_related('user__applications').all()
application_qs_list = [student.user.applications.all() for student in students]
applications = application_qs_list[0].union(application_qs_list[1:])

By default, this will remove duplicate entries. If you want to change this behavior, you can pass all=True to union().

0👍

You need to have related_name attribute set in your ForeignKey field in Application model in order to call it from Student Model. For example:

class Student(models.Model):
    email = models.CharField(max_length=100, unique=True)
    created = models.DateTimeField(auto_now_add=True)

class Application(models.Model):
    student = models.ForeignKey(Student,related_name="applications", on_delete=models.CASCADE)
    """other fields"""

Then you can call it from your student model like this:

students = Student.objects.all().prefetch_related('applications')

You will have list of students. So you need to access each student object and then you can access that particular student’s applications like this:

for student in students:
    app = student.applications

Leave a comment