Skip to content

Support Django's aggregations with output_field #2052

In review

Description

@MartinBernstorff

Describe the Bug

class Default(models.Model):
    int_field = models.IntegerField(default=0)

total_sum_typed = Default.objects.aggregate(
        total=models.Sum("int_field", output_field=models.IntegerField())
)

total_sum_typed should be dict[str, Int], but is dict[str, Any].

Sandbox Link

No response

(Only applicable for extension issues) IDE Information

No response

Activity

  1. MartinBernstorff commented on Jan 9, 2026

    @MartinBernstorff
    Author

    The docs say I should add the django label, but I do not have permissions to add labels :-)

  2. migeed-z commented on Jan 9, 2026

    @migeed-z
    Contributor

    @MartinBernstorff Thank you for the report!
    it is unclear to me if we should be returning dict[str, Int]. The reason is that based on the stubs, the aggregate signature is as follows:
    def aggregate(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ....

    We can consider refining that, but dict[str, Int] seems too strict. Based on the docs:

    When an aggregation is applied to an empty queryset or grouping, the result defaults to its default parameter, typically None. This behavior occurs because aggregate functions return NULL when the executed query returns no rows.

    so it is unclear to me if we should be adding special typechecker handing to refine the type for this.

  3. added
    needs-discussion
    narrowing
    on Jan 9, 2026
  4. MartinBernstorff commented on Jan 12, 2026

    @MartinBernstorff
    Author

    Good points! I still think it should be narrowed down, but I agree that it might not be dict[str, Int].

  5. added
    help wanted
    and removed
    help wanted
    on Jan 26, 2026
  6. github-actions commented on Feb 11, 2026

    @github-actions

    This issue has someone assigned, but has not had recent activity for more than 2 weeks.

    If you are still working on this issue, please add a comment so everyone knows. Otherwise, please unassign yourself and allow someone else to take over.

    Thank you for your contributions!

  7. dhruvparanjape commented on Nov 23, 2026

    @dhruvparanjape
    Contributor

    The same expression types are missing on annotate() attributes (they are Unknown), filed as #5734 with a repro. One rule for what each aggregate/expression returns (using output_field when given) would cover both aggregate() here and annotate() there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

djangohas-open-prnarrowingneeds-discussion

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions