How to join 3 tables in query with Django

后端 未结 1 1836
小蘑菇
小蘑菇 2021-02-10 02:32

models.py

class Employee(models.Model):
    emp_no = models.IntegerField(primary_key=True)
    first_name = ...
    last_name = ...

    # emp_no first_name  las         


        
相关标签:
1条回答
  • 2021-02-10 02:54

    "select_related"

    Returns a QuerySet that will “follow” foreign-key relationships.

    from django.db import models
    class City(models.Model):
        # ...
        pass
    class Person(models.Model):
        # ...
        hometown = models.ForeignKey(
            City,
            on_delete=models.SET_NULL,
            blank=True,
        null=True,
        )
    
    class Book(models.Model):
        # ...
        author = models.ForeignKey(Person, on_delete=models.CASCADE)
    

    then a call to Book.objects.select_related('author__hometown')

    For your exmaples:

    class EmpList(ListView):
        queryset = DeptEmp.objects.all().select_related('emp_no').select_related('dept_no')
    

    employee_list.html

    {% for deptemp in object_list %}
        {{ deptemp.emp_no.first_name }}
        {{ deptemp.emp_no.last_name }}
        {{ deptemp.dept_no.dept_name }}
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题