代码之家  ›  专栏  ›  技术社区  ›  AlxVallejo

Django-如何访问prefetch\u相关字段?

  •  3
  • AlxVallejo  · 技术社区  · 7 年前
    students = Student.objects.prefetch_related('user__applications').all()
    
    students.user__applications # Error
    

    因此,学生拥有与应用程序列表关联的用户对象的外键。但是如何从Student对象访问应用程序列表?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Daniel Roseman    7 年前

    也不 prefetch_related 也没有 select_related 更改访问相关数据的方式;您可以通过字段或反向关系进行操作,就像不使用这些方法一样。

    在本例中,您有一个由学生组成的查询集;每一个都有一个 user 属性,该属性为用户对象提供 applications 提供另一查询集的字段。例如:

    students[0].user.applications.all()[0]
    
        2
  •  0
  •   SK. Fazlee Rabby    7 年前

    你需要 related_name 属性集 ForeignKey 字段输入 Application 模型,以便从调用它 Student 模型例如:

    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"""
    

    然后你可以从你的学生模型中这样调用它:

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

    你将有学生名单。因此,您需要访问每个学生对象,然后才能访问特定学生的应用程序,如下所示:

    for student in students:
        app = student.applications