简体   繁体   English

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

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

I have a djano model: 我有一个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)

What I need to do is to fetch that instance of Expiration that has the smallest number of Profiles associated with it and in case of duplicate, return one of them. 我需要做的是获取与其关联的Profiles数量最少的Expiration实例,如果重复,则返回其中一个。 Or better say if exp is an instance of Expiration, I am looking for the exp with smallest exp.profile_set.count() 或更佳地说,如果exp是Expiration的实例,我正在寻找具有最小exp.profile_set.count()exp

Anyone has any idea? 有人知道吗?

Annotate your query set with the number of profiles for each expiration. 用每个到期的配置文件数注释查询集。 Then order by the annotated field. 然后按带注释的字段排序。 The profile with the fewest (or joint fewest) profiles is the first result of the query set. 具有最少(或联合最少)配置文件的配置文件是查询集的第一个结果。

Putting it all together, you have: 放在一起,您将拥有:

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