Django filter queryset __in 精确匹配

Django filter queryset __in exact matching

我有以下型号:

class Skill(models.Model):
    name = models.CharField(max_length=100, default="")

class Permit(models.Model):
    name = models.CharField(max_length=50)
    skill_course = models.ManyToManyField(
        Skill, related_name="+", blank=True,
    )

class Course(models.Model):
    name = models.CharField(max_length=50)
    skills = models.ManyToManyField(
        Skill, related_name="courses",blank=True,
    )

我想过滤那些与课程中存在的技能完全匹配的许可对象(技能在课程中),所以我过滤了列表课程和技能,如下所示:

course = Course.objects.filter(students=self.request.user, date__lt=datetime.datetime.today())
skills = list(Skill.objects.filter(courses__in=course).distinct())
queryset = Permit.objects.filter(skill_course__in=skills)

但这是模糊匹配,不是精确匹配。例如:

# only if list permit_a = user.skill_a, current user will get permit_a
permit_a = [A, B, C, D]
user.skill_a = [A, B, C, D]

但现在 user.skill_a = [B, E, F],当前用户已经得到 permit_a,我现在被困住了,非常感谢任何建议,在此先感谢。

skills 需要是值列表而不是查询集对象。使用 values_list 从您感兴趣的技能对象中获取值列表。

skills = Skill.objects.filter(courses__in=course).values_list('FIELD_OF_INTEREST', flat=True)

根据您的模型和观点,您需要定义skill_courses许可需求,如下所示:

permit = get_object_or_404(Permit, pk=1)
skill_courses = permit.skill_course.all()

然后你需要把技能改成'exact matching'如下:

queryset = Permit.objects.filter(skill_course__in=[skill for skill in skill_courses if skill in skills])