过滤在其关系模型上没有满足特定记录的对象

Filter objects which has no specific record met on its relational model

假设我有这个模型

class Employee(models.Model):
    name = models.CharField(max_lenght=25)

class Attendance(models.Model):
    employee = ForeignKey(Employee, on_delete=models.CASCADE)

    is_present = models.BooleanField()

这是我的实现:

Employee.objects.bulk_create([
    Employee(name='Greg'),
    Employee(name='John'),
    Employee(name='Lesley'),
])

emp1 = Employee.objects.get(name='Greg')
emp1.attendance_set.create(is_present=True)
emp1.attendance_set.create(is_present=True)
emp1.attendance_set.create(is_present=True)

emp2 = Employee.objects.get(name='John')
emp2.attendance_set.create(is_present=True)
emp2.attendance_set.create(is_present=True)
emp2.attendance_set.create(is_present=True)

emp3 = Employee.objects.get(name='Lesley')
emp3.attendance_set.create(is_present=True)
emp3.attendance_set.create(is_present=False)

现在我如何从没有 Attendance.is_present=False 的员工级别过滤员工,这将产生 Greg 和 John 的不同记录?

到目前为止我试过了,但它包括 Lesley

Employee.objects.filter(attendance__is_present=True).distinct()

使用:

Attendance.objects.filter(is_present=True)

像这样的东西应该有用 -

employees = [attendance.employee for attendance in Attendance.objects.filter(is_present = False)]

我能够使用 exclude()

过滤正确的查询集

首先,如果您有一些所需的查询条件需要包含到查询集中,您可以执行 filter() 函数,然后执行 exclude() 函数,该函数将删除所有具有记录的 Employee 对象attendance__is_present=False

Employee.objects.filter(
    # some criteria..
).exclude(
    attendance__is_present=False
).distinct()

如果除了attendance__is_present=False没有其他标准,你可以直接按照@Piyush S. Wanare回答的那样做。

你可以直接这样做:

Employee.objects.exclude(
    attendance__is_present=False
).distinct()