简体   繁体   English

如何获得在 Django 中使用模型关系的次数?

[英]how to get count of using model relation in django?

I have 2 models 1 is Job Model which is something like this我有 2 个模型 1 是工作模型,它是这样的

class Job(models.Model):
    name=models.CharField(max_length=500,null=False,blank=False)
    description=models.TextField(max_length=5000,null=True,blank=True)
    slug=AutoSlugField(populate_from='name',null=True, blank=True)
    industry=models.ForeignKey('Industry',null=True, blank=True, on_delete=models.SET_NULL)

and other model is Industry model.其他模型是行业模型。 This model has one to one relation with Job model Industry model is like this这个模型和 Job 模型是一一对应的 行业模型是这样的

class Industry(models.Model):
    name=models.CharField(max_length=2000,null=True, blank=True)

Now what i'm trying to do is to get count of jobs against each indsutry using industry model like this现在我要做的是使用这样的行业模型来计算每个行业的工作数量

{% for industry in industry_2 %}
                      <li><a href="#"><h6 class="category-title">{{ industry.name }}</h6> <span class="category-count">{{ industry.jobs_count }}</span> </a></li>
                      {% endfor %}

but its not working for me, please help me in this regard to solve this issue.但它对我不起作用,请在这方面帮助我解决这个问题。 Do suggest any better method also, Thanks也请建议任何更好的方法,谢谢

you can use您可以使用

{% for industry in industry_2 %}
    <li><a href="#"><h6 class="category-title">{{ industry.name }}</h6> <span class="category-count">{{ industry.job_set.count }}</span> </a></li>
{% endfor %}

Please, note that by default, ie if you do not use related_name on a ForeignKey , the related name is lowercased model name suffixed with _set , which makes sense, it's a job set of an industry.请注意,在默认情况下,也就是说,如果你不使用related_nameForeignKey与后缀,相关的名称是小写的型号名_set ,这是有道理的,这是一个工作组的一个行业。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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