python - what about saving extra variable in a QuerySet? -


for example have queryset folder=folder.objects.all().

what saving variable in

for in folder:     i.fcount = 33 

so can use in templates like:

{% folder in folders %}{{ folder.fcount }}{% endfor %} 

i using in 1 of page:

models.py

class folder(models.model):     employer=models.foreignkey(employer)     name=models.charfield(max_length=100)         lastupdate= models.datetimefield(auto_now=true)  class savedcandidatemanager(models.manager):     def itemcount(self,fd):         return self.filter(folder=fd).count()      class savedcandidate(models.model):     folder=models.foreignkey(folder)         candidate=models.foreignkey(jobseeker)     created=models.datetimefield(auto_now_add = true)     objects=savedcandidatemanager() 

views.py

def folder(request):      folder=folder.objects.filter(employer=request.user.employer)     in folder:         i.fcount=savedcandidate.objects.itemcount(i)     return render(request,'employer/pages/candidatefolder.html', {'folders':folder}) 

candidatefolder.html

 {% folder in folders %} <tr>     <td>                  <a href="/folder/{{ folder.id }}/" >{{ folder.name }}</a>                 </td>     <td>{{ folder.fcount }}</td>     <td>{{ folder.lastupdate }}</td> </tr> {% endfor %} 

this helpful since can use in templates in forloop look:

{{ folder.fcount }} 

you can use method, this:

folder=folder.objects.all().extra(select = {'fcount':33}) 

so, each f in folder queryset have fcount property.

it works sql alias.

if want use other data based on model have use annotate(https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate), maybe custom aggregation function(https://docs.djangoproject.com/en/dev/topics/db/aggregation/).


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -