1

Consider below example:

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

class ModelY(MPTTModel):

    def root(self):
        return get_root()

    root = property(root)

Now I would like to make query like this

ModelX.objects.filter(fieldX__root=match)

or better yet directly calling get_root() like this

ModelX.objects.filter(fieldX__get_root=match)

which would make the root() method superfluous.

None of the above seem to work though. Why is that?

Nathan Villaescusa
  • 17,331
  • 4
  • 53
  • 56
Milo Wielondek
  • 4,164
  • 3
  • 33
  • 45

1 Answers1

1

.filter() takes as keyword arguments field lookups. From docs:

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.

This means you can not make queries based on model methods. There are some snippets that may help you:

#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)
Serhii Holinei
  • 5,758
  • 2
  • 32
  • 46
  • Thanks, but that's not quite what I was looking for. I want to get all ModelX objects whose fieldX point to a foreignkey that has a certain root. Hope this makes sense. – Milo Wielondek Oct 22 '12 at 17:48
  • `fieldX` should point to a root node or to any descendant of a certain root node? – Serhii Holinei Oct 22 '12 at 17:56
  • One more detail: is there only one certain root node or it can be multiple of them? It is important, because `mptt` has no built in method for `.get_descendants` for a list of nodes. – Serhii Holinei Oct 22 '12 at 18:15
  • Not sure I get what you mean, but no, there should only be one associated root node with each object (that can be accessed via `get_root()`). And so my problem is that I want to get all objects that belong to a specific root node. – Milo Wielondek Oct 22 '12 at 18:26