sql - Django: best way to design one-to-many count viewing -


i have 2 models , b, , 1 model may referenced in several b modals:

class a(model):     name = charfield(...)  class b(model):     name = charfield(...)     = foreignkey(a, related_name='all_b') 

in view of model want show how many b objects there are. this:

args={'a_all': a.objects.all()} ... {% in a_all %}    {{a.name}} : {{ a.all_b.objects.count }} <br> {% endofr %} 

but, sql query every object, , not cool if have many models in db tables.

so, want fetch counts in 1 query. select_related in case can't used, becouse works one-to-one nad many-to-one relations, not one-to-many.

only thing thant comes head add counter field a:

class a(model):     name = charfield(...)     b_count = positiveintegerfield(...) 

and update when change relation. brings many work detect relations change if there many views add/delete/rewrite "a" field of "b" modal.

try this:

a_all = a.objects.all().annotate(b_count =count('b')) 

this add new field b_count every object of a. in template can like

 {% in a_all %}    {{a.name}} : {{ a.b_count }} <br> {% endofr %} 

Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -