通过查询访问MPTT模型的get_root

2024-04-27 05:12:33 发布

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

考虑以下示例:

class ModelX(models.Model):
    fieldX = models.ForeignKey(ModelY)

class ModelY(MPTTModel):

    def root(self):
        return get_root()

    root = property(root)

现在我想提出这样的疑问

^{pr2}$

或者直接打电话给get_root(),这样更好

ModelX.objects.filter(fieldX__get_root=match)

{cd2>会使方法变得多余。在

不过,以上这些似乎都不管用。为什么?在


Tags: self示例getmodelreturnmodelsdefproperty
1条回答
网友
1楼 · 发布于 2024-04-27 05:12:33

.filter()接受关键字参数field lookups。来自文档:

Changed in Django 1.4: The field specified in a lookup has to be the name of a model field. There's one exception though, in case of a ForeignKey you can specify the field name suffixed with _id. In this case, the value parameter is expected to contain the raw value of the foreign model's primary key.

这意味着您不能基于模型方法进行查询。有一些片段可以帮助您:

#returns all ModelX objects related to root nodes
ModelX.objects.filter(fieldX__level=0)

#first: get descendants of root node with id=1 (it can be any field lookups)
#second: get all ModelX nodes, related to previously founded nodes
nodes = ModelY.object.get(level=0, id=1).get_descendants()
ModelX.objects.filter(fieldX__in=nodes)

相关问题 更多 >