在Django ORM中,如何在反向集查询中获得计数

时间:2018-08-05 19:07:16

标签: python django django-models django-orm

我有以下三种模型:

class Member (models.Model):
    FederationID = models.FloatField(unique=True)
    User = models.ForeignKey(User, on_delete=models.CASCADE)
    height = models.IntegerField(blank=True, null=True)
    eye = models.CharField(blank=True, null=True, max_length=10)
    hair = models.CharField(blank=True, null=True, max_length=10)
    birthdate = models.DateField()
    bio = models.TextField()
    Address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True)
    Phone = models.ForeignKey(Phone, on_delete=models.CASCADE, null=True, blank=True)
    Photos = models.ManyToManyField(Photos)
    Rank = models.ManyToManyField('Rank', through='Promotion')
    Unit = models.ManyToManyField('Unit', through='Assignment')

class Genre(models.Model):
    ShortName = models.CharField(max_length=50)
    LongName = models.CharField(max_length=500)

    def __str__(self):
        return self.LongName + ' (' + self.ShortName + ')'


class Career(models.Model):
    ShortName = models.CharField(max_length=50)
    LongName = models.CharField(max_length=500)

    def __str__(self):
        return self.LongName + ' (' + self.ShortName + ')'


class Rank(models.Model):
    RANK_TYPE_CHOICES = (
        ('O', 'Officer'),
        ('E', 'Enlisted'),
        ('V', 'Civilian'),
        ('C', 'Cadet'),
    )
    ShortName = models.CharField(max_length=50)
    LongName = models.CharField(max_length=500)
    Type = models.CharField(max_length=1, choices=RANK_TYPE_CHOICES, default='O')
    Genre = models.ForeignKey(Genre, on_delete=models.DO_NOTHING)
    Career = models.ForeignKey(Career, on_delete=models.DO_NOTHING)
    image = models.ForeignKey(Photos, on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.LongName + ' (' + self.Career.LongName + ') from ' + self.Genre.LongName


class Promotion(models.Model):
    Rank = models.ForeignKey(Rank, on_delete=models.DO_NOTHING)
    Member = models.ForeignKey(Member, on_delete=models.CASCADE)
    PromotionDate = models.DateField(default=now)

    def __str__(self):
        return self.Member.User.first_name + ' ' + self.Member.User.last_name + ' promoted to ' + self.Rank.LongName + ' on ' + str(self.PromotionDate)

我通过推广在Rank和Member之间建立了多对多关系。
在模型Rank中,我有Type字段。

我需要对每个成员的最新促销进行计数并按类型字段分组。

像这样:{'officer':4, 'enlisted':2, 'Civilian':12}

我添加了这个以获得每个成员的排名:

self.promotion_set.latest('PromotionDate').Rank

但是我需要这个组。

我很感谢在这里的任何智慧。谢谢

0 个答案:

没有答案