【问题标题】:I want add two annotation for two foreign keys using Django. How do I do this?我想使用 Django 为两个外键添加两个注释。我该怎么做呢?
【发布时间】:2019-11-19 19:37:07
【问题描述】:
# models.py
from django.db import models

class Elephant(models.Model):
    location = models.ForeignKey(Location, on_delete=models.CASCADE)
    families = models.ForeignKey(Families, on_delete=models.CASCADE)

def add_families_and_locations_counts(elephants):
    return elephants.annotate(
            families_number=Count('families'),
            location_number=Count('location')
    )
# Run
output = add_families_and_locations_counts(elephants)

在上面,计数不正确。如何获得正确的计数?

【问题讨论】:

标签: django foreign-keys


【解决方案1】:

您想要计算不同的外键模型实例。

将您的注释功能更新为以下内容:

def add_families_and_locations_counts(elephants):
    return elephants.annotate(
            families_number=Count('families', distinct=True),
            location_number=Count('location', distinct=True)
    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    相关资源
    最近更新 更多