我有两个公司和雇员模型,必须显示如下记录
Company Name, Number of Employee
```python
class Company(models.Model):
name=models.CharField(max_length=20)
est=models.IntegerField(max_length=4)
class employee(models.Model):
name=models.CharField(max_length=20)
company=models.ForeignKey(Company)
```
如何编写Django ORM模型以获取详细信息?
答案 0 :(得分:2)
from django.db.models import Count
Company.objects.values('name').annotate(emp_count=Count('employee'))
这将生成一个QuerySet
对象,
In [3]: Company.objects.values('name').annotate(emp_count=Count('employee'))
...:
Out[3]: <QuerySet [{'name': 'company_name_1', 'emp_count': 3}, {'name': 'company_name_2', 'emp_count': 2}]>
答案 1 :(得分:0)
您可以这样在外键关系中放入 related_name() :
class Company(models.Model):
name=models.CharField(max_length=20)
est=models.IntegerField(max_length=4)
class employee(models.Model):
name=models.CharField(max_length=20)
company=models.ForeignKey(Company, related_name='employees')
然后使用Count从员工模型中获取计数并将值注释至queryset。像这样:
from django.db.models import Count
Company.objects.annotate(employee_count=Count('employees')) # same as related_name defined in employee model