[英]Filtering by ManyToMany field length: values_list() returns, but the filtering result is empty
I have such a model in Django
:我在 Django 中有这样的Django
:
class VariantTag():
saved_variants = models.ManyToManyField('SavedVariant')
variant_tag_type = models.ForeignKey('VariantTagType', on_delete=models.CASCADE)
Then, I am trying to get the VariantTag
models with saved_variants
field of length 2
which contain at least one of the id from the variant_ids
pk
list:然后,我试图获取长度为2
的saved_variants
字段的VariantTag
模型,其中至少包含一个来自variant_ids
pk
列表的 id:
het_tags = (VariantTag.objects.annotate(variant_len=Count('saved_variants'))) \
.filter(saved_variants__in=variant_ids, variant_len=2)
logger.info(het_tags.all())
het_variant_ids = het_tags.values_list('saved_variants', flat=True)
logger.info('******* het_variant_ids: {}'.format(het_variant_ids))
Logger
output that I get is the following:我得到的Logger
output 如下:
<QuerySet []>
******* het_variant_ids: <QuerySet [150, 149]>
Where 150
and 149
are correct ids that I am looking for.其中150
和149
是我正在寻找的正确 ID。 However, I need to get full QuerySet
objects, how to get them?但是,我需要获取完整的QuerySet
对象,如何获取它们? Why is it not working?为什么它不起作用?
Update更新
Both query conditions are working on their own separately, but applied together they give an empty result.两个查询条件各自独立工作,但一起应用它们会给出一个空结果。 According to the data I have in the models that should not happen.根据我在不应该发生的模型中的数据。
I am not sure why but restructuring of the query to do the filtering first for ids, then annotation, and only then filtering by length of ManyToMany
field worked out:我不知道为什么,但重组查询首先对 id 进行过滤,然后是注释,然后才按ManyToMany
字段的长度进行过滤:
het_tags = (VariantTag.objects.filter(saved_variants__in=variant_ids)
.annotate(variant_len=Count('saved_variants')))
.filter(variant_len=2)
If you have any idea of why this works, please, post another answer.如果您知道为什么会这样,请发布另一个答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.