【发布时间】:2021-06-07 08:27:50
【问题描述】:
这是我模型的形状。
class SomeModel(model):
some_field = models.DateTimeField(blank=True, null=True)
class OtherModel(Model):
list_of_some_models = models.ManyToManyField(SomeModel)
我有一本这样的字典,其中列表中的每个元素都是 SomeModel pk:
{
"list_of_some_models": [1, 10, 12, 20]
}
我想检查是否已经有一条记录与 ID 为 1、10、12 和 20 的 SomeModel 有关系。
有可能吗?
【问题讨论】:
-
试试这个
OtherModel.objects.filter(list_of_some_models__in=[1, 10, 12, 20]) -
它返回 4 个相同的 OtherModel 实例,因为我猜它为列表中的每个 pk 找到 1 个 OtherModel...我想找到 1 个同时与所有 4 SomeModel 有关系的 OtherModel
-
使用
.distinct()删除重复项。 -
它不起作用,因为如果我执行 OtherModel.objects.filter(list_of_some_models__in=[10]) 它将找到具有 list_of_some_models = [1, 10, 12, 20] 的 OtherModel
标签: django django-models