I have a djano model:
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. Or better say if exp is an instance of Expiration, I am looking for the exp with smallest exp.profile_set.count()
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: