我有以下型号:
class Volunteer(models.Model): first_name = models.CharField(max_length=50L) last_name = models.CharField(max_length=50L) email = models.CharField(max_length=50L) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) class Department(models.Model): name = models.CharField(max_length=50L, unique=True) overseer = models.ForeignKey(Volunteer, blank=True, null=True) location = models.CharField(max_length=100L, null=True) class DepartmentVolunteer(models.Model): volunteer = models.ForeignKey(Volunteer) department = models.ForeignKey(Department) assistant = models.BooleanField(default=False) keyman = models.BooleanField(default=False) captain = models.BooleanField(default=False) location = models.CharField(max_length=100L, blank=True, null=True)
我想查询所有未分配志愿者的部门。我可以使用以下查询进行操作:
SELECT vsp_department.name FROM vsp_department LEFT JOIN vsp_departmentvolunteer ON vsp_department.id = vsp_departmentvolunteer.department_id WHERE vsp_departmentvolunteer.department_id IS NULL;
有没有一种更像django的方式做到这一点,还是我应该只使用原始sql?
您可以通过遵循查找中的向后关系来执行此操作。
>>> qs = Department.objects.filter(departmentvolunteer__isnull=True).values_list('name', flat=True) >>> print(qs.query) SELECT "app_department"."name" FROM "app_department" LEFT OUTER JOIN "app_departmentvolunteer" ON ( "app_department"."id" = "app_departmentvolunteer"."department_id" ) WHERE "app_epartmentvolunteer"."id" IS NULL
以下是有关“跨多值关系”查询的文档:https : //docs.djangoproject.com/en/stable/topics/db/queries/#spanning-multi-valued- relationships