python - Writing a django query the other way -



python - Writing a django query the other way -

i have simple forum-app:

class board(models.model): title = models.charfield(max_length=100) class topic(models.model): board = models.foreignkey(board) title = models.charfield(max_length=100) class post(models.model): topic = models.foreignkey(topic) body = models.textfield()

i want count postings in board. 1 way call:

class board(...): ... def post_count(self): homecoming post.objects.filter(topic__board=self).count()

but there way not starting post.objects board-model? board.objects...? don't need farther method in board class , utilize builtin?

you can utilize related managers each of objects have foreign key pointing @ them create queries other side of foreign key relationships. default, these so-called reverse related managers named {model-with-foreign-key}_set, , exist on object of model pointed @ model's foreign key relationship.

here's django documentation has traversing relationships in reverse order.

here's illustration of working backwards through relationships using suggested problem:

class board(models.model): ... def post_count(self): count = 0 topic in self.topic_set: count += topic.post_set.count() homecoming count

your initial method seems more readable me, though.

python django python-2.7 django-models django-queryset

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -