开发者

Django: get count of ForeignKey item in template?

开发者 https://www.devze.com 2022-12-26 04:36 出处:网络
Straightforward question - apologies if it is a duplicate, but I can\'t find the answer if so. I have a User model and a Submission model, like this:

Straightforward question - apologies if it is a duplicate, but I can't find the answer if so.

I have a User model and a Submission model, like this:

class Submission(models.Model):
    uploaded_by = models.ForeignKey('User')
class User(models.Model):
    name = models.CharField(max_length=250 )

How can I show the number 开发者_JS百科of Submissions made by each user in the template? I've tried {{ user.submission.count }}, like this:

for user in users:
    {{ user.name }} ({{ user.submission.count }} submissions)

but no luck...


Try this

{{user.submission_set.all|length}}


You forgot the "set". It should be {{ user.submission_set.count }}. You can always change the related name, but the default is <fk class name>_set. For more see the relations documentation.

0

精彩评论

暂无评论...
验证码 换一张
取 消