获取对象的计数

时间:2014-12-10 12:21:30

标签: python django

我想获得所有医生的专业化计数,并希望在管理面板中显示

以下是模型

class Doctor(models.Model):
    name = models.CharField(max_length=1300)
    specialization = models.ForeignKey(Specialization)
    clinic = models.ForeignKey(Clinic)

class Specialization(models.Model):
    name = models.CharField(max_length=30)

例如,我希望显示如下:

皮肤科医生:10

眼科医生:15

我对Django很新,并且不知道如何去做。

3 个答案:

答案 0 :(得分:1)

您可以通过这种方式完成此任务,例如:

#admin.py
class SpecializationAdmin(admin.ModelAdmin):
    list_display = ('get_count',)
    def get_count(self, obj):
        return u"{}: {}".format(obj.name, obj.doctor_set.count())
    get_count.short_description = "Number of Doctors"

并将其注册为:

# also in admin.py
admin.site.register(Specialization, SpecializationAdmin)

不要忘记将Specialization模型导入admin.py

答案 1 :(得分:1)

不要使用obj.doctor_set.count()食谱。将为每个专业化记录调用此方法。

将单个SQL查询与聚合一起使用:

# admin.py
from django.contrib import admin
from django.db.models import Count
from app.models import Specialization

class SpecializationAdmin(admin.ModelAdmin):

    list_display = ['name', 'doctor_count_display']

    def get_queryset(self, request):
        qs = super(SpecializationAdmin, self).get_queryset(request)
        return qs.annotate(doctor_count=Count('doctor')).order_by('-doctor_count')

    def doctor_count_display(self, obj):
        return obj.doctor_count
    doctor_count_display.short_description = 'Number of doctors'
    doctor_count_display.admin_order_field = 'doctor_count'

admin.site.register(Specialization, SpecializationAdmin)

答案 2 :(得分:0)

您需要了解查询Django Queries

显示皮肤科医生的数量:

Doctor.objects.filter(specialization__name="Dermatologist").count()

显示眼科医生的数量

Doctor.objects.filter(specialization__name="Ophthalmologist").count()