Ho to "create" a field in a queryset to show in my template?

16 views
Skip to first unread message

Fellipe Henrique

unread,
Mar 23, 2015, 12:48:36 PM3/23/15
to Django Users
Hello,

I have these view:

def planos_view(request, cat_id=0):
if cat_id == '0':
categorias = Categoria.objects.filter(publicado=True)
else:
categorias = Categoria.objects.filter(publicado=True).filter(id=cat_id)

for c in categorias:
c.total = Plano.objects.filter(categoria=c).count()

return render_to_response('planos.html', locals(),
context_instance=RequestContext(request))
I want to add the "total" field in my "categories" model.. What's the best approach for these, because these code above don't work...

Thanks agains 

T.·.F.·.A.·.     S+F
Fellipe Henrique P. Soares

e-mail: > echo "lkrrovknFmsgor4ius" | perl -pe \ 's/(.)/chr(ord($1)-2*3)/ge'
Twitter: @fh_bash

Masklinn

unread,
Mar 23, 2015, 12:57:18 PM3/23/15
to django...@googlegroups.com
Adding it as a regular property to your Categories class should work:

    # inside Categoria
    @property
    def total(self):
        return Plano.object.filter(categoria=self).count()

You may also want to use backward relationship links to simplify the
code and make it more robust, but I don't know how your models are
setup. If it's just an FK without an explicit related_name, should be 
something along the lines of:

    @property
    def total(self):
        return self.plano_set.count()

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAF1jwZGvrVY2PG8YCgR3r4LS8URaR6-V2rP_EW3j9RJMpkVr3A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Fellipe Henrique

unread,
Mar 23, 2015, 1:02:13 PM3/23/15
to Django Users
Ok,

But, if I want to create some "fields" in RunTime, I thinking to use Dict, but I don't know what to use to create "temporary" queryset...
Reply all
Reply to author
Forward
0 new messages