请帮助我,我已经被困在这个问题上太久了:(
我有这两个模型:
class Specialization(models.Model):
name = models.CharField("name", max_length=64)
class Doctor(models.Model):
name = models.CharField("name", max_length=128)
# ...
specialization = models.ForeignKey(Specialization)
Run Code Online (Sandbox Code Playgroud)
我想用具有该专业的医生数量来注释查询集中的所有专业。
我经历了一个循环并做了一个简单的: Doctor.objects.filter(specialization=spec).count()然而事实证明这太慢而且效率低下。我读得越多,就越意识到使用此处SubQuery来筛选专业化的医生是有意义的OuterRef。这就是我想出的:
doctors = Doctor.objects.all().filter(specialization=OuterRef("id")) \
.values("specialization_id") \
.order_by()
add_doctors_count = doctors.annotate(cnt=Count("specialization_id")).values("cnt")[:1]
spec_qs_with_counts = Specialization.objects.all().annotate(
num_applicable_doctors=Subquery(add_doctors_count, output_field=IntegerField())
)
Run Code Online (Sandbox Code Playgroud)
对于每个专业,我得到的输出仅为 1。代码只是用它来注释每个医生对象specialization_id,然后注释该组内的计数,这意味着它将是 1。
不幸的是,这对我来说并不完全有意义。在我最初的尝试中,我使用了一个聚合来进行计数,虽然它可以单独工作,但它不能作为 a 工作SubQuery,但我收到此错误:
This queryset contains a reference to an outer query and may only be used in a subquery.
我之前发布过这个问题,有人建议这样做Specialization.objects.annotate(count=Count("doctor"))
然而,这不起作用,因为我需要计算特定的医生查询集。
但是,我没有得到相同的结果:
python django django-aggregation django-annotate django-subquery
这是用Angularjs制作的非常干净且易于使用的日历。
https://mattlewis.me/angular-bootstrap-calendar/
如果您单击任一天边缘的数字,则将切换到日视图。我想禁用它,但我不知道如何。
请帮忙。