计算模型中某些选择的出现次数
Count the number of occurrences of certain choices in models
我有以下型号:
class Team(models.Model):
# stuff
class Event(models.Model):
# stuff
class Award(models.Model):
award_type_choices = (
(1, "some string"), # a lot of these
(2, "some other str"),
)
award_type = models.CharField(choices=award_type_choices)
specific_choices = (
(1, "some string"), # etc
# only a few of these, but all of these can be found inside award_type_choices.
)
event = models.ForeignKey(Event)
recipients = models.ManyToManyField(Team)
我正在尝试 count/annotate Team
赢得符合 specific_choices
顺序的奖项的次数。我可以通过这段代码过滤获奖的队伍:
reversed_choices = dict((v, k) for k, v in Award.specific_choices)
Team.objects.filter(award__award_type__in=reversed_choices.values())
但是,我不确定我应该如何计算这些。我以前用过 Count
、F
和 ExpressionWrapper
,但没有广泛地了解如何立即执行此操作。
我想我可以通过将与 filter
相同的参数放入 Count
对象来实现它,但是当我输入它时我意识到它不起作用,即:
Team.objects.annotate(num_specifics=Count('award__award_type__in=Award.specific_choices'))
如有任何帮助,我们将不胜感激。
choices = Award.specific_choices.all()
c = Team.objects.filter(award__award_type__in=choices).count()
我找到了一些关于 Conditional Aggregation 的 Django 文档,帮助我解决了这个问题。
def most_specifics():
reverse_specs = dict((v, k) for k, v in Award.specific_choices)
return Team.objects.annotate(
c=Sum(
Case(
When(award__award_type__in=reverse_specs.values(), then=1),
default=0,
output_field=PositiveSmallIntegerField(),
)
)
).order_by('-c')
以下代码将查找给定模型的特定字段中的选择数量:
my_field=Model._meta.get_field('field_name')
length=len(my_field.choices._display_map)
我有以下型号:
class Team(models.Model):
# stuff
class Event(models.Model):
# stuff
class Award(models.Model):
award_type_choices = (
(1, "some string"), # a lot of these
(2, "some other str"),
)
award_type = models.CharField(choices=award_type_choices)
specific_choices = (
(1, "some string"), # etc
# only a few of these, but all of these can be found inside award_type_choices.
)
event = models.ForeignKey(Event)
recipients = models.ManyToManyField(Team)
我正在尝试 count/annotate Team
赢得符合 specific_choices
顺序的奖项的次数。我可以通过这段代码过滤获奖的队伍:
reversed_choices = dict((v, k) for k, v in Award.specific_choices)
Team.objects.filter(award__award_type__in=reversed_choices.values())
但是,我不确定我应该如何计算这些。我以前用过 Count
、F
和 ExpressionWrapper
,但没有广泛地了解如何立即执行此操作。
我想我可以通过将与 filter
相同的参数放入 Count
对象来实现它,但是当我输入它时我意识到它不起作用,即:
Team.objects.annotate(num_specifics=Count('award__award_type__in=Award.specific_choices'))
如有任何帮助,我们将不胜感激。
choices = Award.specific_choices.all()
c = Team.objects.filter(award__award_type__in=choices).count()
我找到了一些关于 Conditional Aggregation 的 Django 文档,帮助我解决了这个问题。
def most_specifics():
reverse_specs = dict((v, k) for k, v in Award.specific_choices)
return Team.objects.annotate(
c=Sum(
Case(
When(award__award_type__in=reverse_specs.values(), then=1),
default=0,
output_field=PositiveSmallIntegerField(),
)
)
).order_by('-c')
以下代码将查找给定模型的特定字段中的选择数量:
my_field=Model._meta.get_field('field_name')
length=len(my_field.choices._display_map)