繁体   English   中英

如何在Django中找到具有最小related_set的对象?

[英]How to find the object with smallest related_set in Django?

我有一个djano模型:

class Expiration(models.Model):
    UNIT_CHOICES = (
        ('M', 'Month'),
        ('W', 'Week')
    )
    unit    =   models.CharField(max_length = 1, choices= UNIT_CHOICES)
    number_of_units = models.IntegerField(default=1)
    offset = models.IntegerField(default=1)

class Profile(models.Model):
    name          = models.CharField(default="tmp", max_length=32, blank=True)
    expiration_period = models.ForeignKey(Expiration, blank=True, null=True)

我需要做的是获取与其关联的Profiles数量最少的Expiration实例,如果重复,则返回其中一个。 或更佳地说,如果exp是Expiration的实例,我正在寻找具有最小exp.profile_set.count()exp

有人知道吗?

用每个到期的配置文件数注释查询集。 然后按带注释的字段排序。 具有最少(或联合最少)配置文件的配置文件是查询集的第一个结果。

放在一起,您将拥有:

from django.db.models import Count

Expiration.objects.annotate(num_profiles=Count('profile')).order_by('num_profiles')[0]

暂无
暂无

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

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