基于多对多字段过滤 - 如果项目在列表中,则获取记录

2024-10-04 07:32:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有一种方法可以让我根据许多领域进行筛选。我知道有一个__in过滤器,但似乎这个过滤器需要一个id,而我没有id(我可以得到id,但我想知道没有它是否可能)。 这就是我的模型

class modelEmployee(models.Model):
    user                = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
    title               = models.CharField(max_length=200, unique=False, blank=False, null=True)
    skills              = models.ManyToManyField(modelSkill, blank=True)

class modelJob(models.Model):
    skills              = models.ManyToManyField(modelSkill,blank=True)
    title               = models.CharField(max_length=200, unique=False,blank=False,null=True)

这是多对多的模型

class modelSkill(models.Model):
    skill_description   = models.CharField(max_length=50, unique=True)

现在我有一张这样的单子

  skillList = [SkillA,SkillB,SkillC...] #Description field

目前我不可能这么做

modelJob.objects.filter(skills__in=skillList)

我不能这样做的原因是因为skills\uu in需要一个包含技能id号的列表,而不是其他技能域。我的问题是如何告诉skills\u我传递的列表是skill_descriptionmodelSkill而不是id?你知道吗

更新: 如果我这么做

  queryset_list = modelEmployee.objects.filter(skills___skill_description__in=skill_filter)

我得到了错误

raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0]))
django.core.exceptions.FieldError: Related Field got invalid lookup: _skill_description

Tags: inidfalsetruemodelmodelsdescriptionnull
1条回答
网友
1楼 · 发布于 2024-10-04 07:32:20

您可以更深入地挖掘一层,并特别匹配skill_description字段:

modelJob.objects.filter(skills__skill_description__in=skillList)

来自Django文档:

For example, if an Entry has a ManyToManyField called tags, we might want to find entries linked to tags called “music” and “bands” or we might want an entry that contains a tag with a name of “music” and a status of “public”.

To handle both of these situations, Django has a consistent way of processing filter() calls. Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects, but for multi-valued relations, they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.

That may sound a bit confusing, so hopefully an example will clarify. To select all blogs that contain entries with both “Lennon” in the headline and that were published in 2008 (the same entry satisfying both conditions), we would write:

Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)

https://docs.djangoproject.com/en/2.1/topics/db/queries/#spanning-multi-valued-relationships

相关问题 更多 >