Django 查询匹配 'cousin' objects(具有相同的祖父母)
Django query for matching 'cousin' objects (with same grandparent)
我正在尝试对表单输入进行一些验证,并且需要检查正在创建的实例是否已存在于同一个祖父母下。我要验证的字段不是主键,因为它可以存在于 'family' 之外。
我似乎想不出一个合适的查询,但到目前为止我有以下有效的方法:
existing_parents = Parent.objects.filter(grandparent=active_parent.grandparent)
for parent in existing_parents:
existing_children = parent.children.all()
for children in existing_children
if existing_children.identifier == identifier:
self._errors["form_field"] = self.error_class(
["That child already exists"]
)
else:
pass
只是想知道是否有我可以做的查找来简化它?
是,您可以通过以下方式检查:
Child.objects.filter(
<b>identifier=identifier</b>,
<b>parent__grandparent__parents=<i>active_parent</i></b>
).exists()
因此我们从Child
模型开始,向上移动到grandparent
(parent__grandparent
然后向下移动__parents
,并检查这样的标识符已经存在)。这里 parents
是该名称的 related_query_name=…
[Django-doc] of the ForeignKey
s from Parent
to GrandParent
, and from Child
to Parent
. If you did not specify a related_query_name=…
parameter, it will use the related_name=…
[Django-doc] 的值,如果您也没有指定,那么它将使用小写的模型名称。
这当然会检查所有 个孙子,包括您要编辑并且已经存在于数据库中的孙子。因此,您可以 排除 一个 Child
已经存在于:
Child.objects.exclude(
<b>pk=<i>pk_of_child_to_exclude</i></b>
).filter(
<b>identifier=identifier</b>,
<b>parent__grandparent__parents=<i>active_parent</i></b>
).exists()
我正在尝试对表单输入进行一些验证,并且需要检查正在创建的实例是否已存在于同一个祖父母下。我要验证的字段不是主键,因为它可以存在于 'family' 之外。 我似乎想不出一个合适的查询,但到目前为止我有以下有效的方法:
existing_parents = Parent.objects.filter(grandparent=active_parent.grandparent)
for parent in existing_parents:
existing_children = parent.children.all()
for children in existing_children
if existing_children.identifier == identifier:
self._errors["form_field"] = self.error_class(
["That child already exists"]
)
else:
pass
只是想知道是否有我可以做的查找来简化它?
是,您可以通过以下方式检查:
Child.objects.filter(
<b>identifier=identifier</b>,
<b>parent__grandparent__parents=<i>active_parent</i></b>
).exists()
因此我们从Child
模型开始,向上移动到grandparent
(parent__grandparent
然后向下移动__parents
,并检查这样的标识符已经存在)。这里 parents
是该名称的 related_query_name=…
[Django-doc] of the ForeignKey
s from Parent
to GrandParent
, and from Child
to Parent
. If you did not specify a related_query_name=…
parameter, it will use the related_name=…
[Django-doc] 的值,如果您也没有指定,那么它将使用小写的模型名称。
这当然会检查所有 个孙子,包括您要编辑并且已经存在于数据库中的孙子。因此,您可以 排除 一个 Child
已经存在于:
Child.objects.exclude(
<b>pk=<i>pk_of_child_to_exclude</i></b>
).filter(
<b>identifier=identifier</b>,
<b>parent__grandparent__parents=<i>active_parent</i></b>
).exists()