Domanda

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?

È stato utile?

Soluzione

.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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top