简体   繁体   中英

django get count of 'children' of related_name field (and do this in template?)

I am trying get the list of HQ (Head Quarter) Field Manager and count of Animal and Agent under Field Manger. Each foreign key has a related name.

Models are

class Fm(models.Model):
    hq    = models.ForeignKey(Hq, on_delete=models.SET_NULL,null=True)
    fm    = models.CharField(max_length=50)

class User(AbstractBaseUser):
    email  = models.EmailField(max_length=255,)
    fm     = models.ForeignKey(Fm,on_delete=models.SET_NULL,related_name="agents")

class Animal(models.Model):
    agent  = models.ForeignKey(User,on_delete=models.SET_NULL,related_name="animals")
    farmer = models.CharField(max_length=50')

View

def print_table(request):
     fms = Fm.objects.all()
     context = {'fms':fms}
     return render(request, 'fm.html',context)

Template

{% for fm in fms %}
    <tr>
       
        <td>{{fm.hq}}</td>
        <td>{{fm.fm}}</td>
        <td>{{fm.agents.animals.all.count}}</td> (Error here)
        <td>{{fm.agents.all.count}}</td>
    </tr>
 {% endfor %}

 Expected OutPut
 HQ   FM_Name  Animal_Count       Agent_Count
 HQ1  Any Name 10 (Not Working)      2

Current Output

 HQ   FM_Name  Animal_Count       Agent_Count
 HQ1  Any Name                       2

This is listing count of Animal but I need sum of all

{% for x in fm.agents.all %}
    <div>{{x.animals.all.count}}</div><br>
{% endfor %}

Anyone Please Help Me

You can pass your data like this from views to template

all_result = []
fms = Fm.objects.all()
for x in fms:
    result = {}
    result['fm']=x.fm
    result['hq']=x.hq
    result['zone']=x.hq.zone
    result['age_count']= User.objects.filter(fm=x).count()
    agents=  User.objects.filter(fm=x)
    result['animal_count']=Animal.objects.filter(agent__in=agents).count() 
    all_result.append(result)

It worked for me let me know if you still have problems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM