我有以下型号:
class Answer(models.Model):
answer = models.CharField(max_length=255)
class Result(models.Model):
description = models.TextField()
answers = models.ManyToManyField(Answer)
鉴于我有一个Answer模型的id列表,如下所示:
answer_list = [1, 3, 5, 16]
有没有办法获得一个Result实例,其中answers字段包含answer_list中的所有id?我不是在寻找与该字段中的项目完全匹配,但所有答案ID都需要存在。
我尝试了以下解决方案,但它寻找完全匹配:
query = Result.objects.filter(answers__in=answers).annotate(num_answers=Count('answers'))
result = query.filter(num_answers=len(answers)).first()
答案 0 :(得分:0)
您应该可以通过重复过滤调用来执行此操作:
query = Result.objects.all()
for answer in answer_list:
query = query.filter(answers=answer)