Opened 3 days ago

Last modified 2 days ago

#36051 assigned New feature

Count CompositePrimaryKey field targets toward function arity check

Reported by: Jacob Walls Owned by: Jacob Walls
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Calling a database function with an incorrect number of arguments raises TypeError if the function declares its arity. We could improve the DX around CompositePrimaryKey by leveraging this feature, instead of just advising to be careful.

The docs sort of imply some kind of error is raised ("# ERROR"), but this test passes:

  • tests/composite_pk/test_aggregate.py

    diff --git a/tests/composite_pk/test_aggregate.py b/tests/composite_pk/test_aggregate.py
    index b5474c5218..750618a277 100644
    a b  
    11from django.db import NotSupportedError
    2 from django.db.models import Count, Q
     2from django.db.models import Count, Max, Q
    33from django.test import TestCase
    44
    55from .models import Comment, Tenant, User
    class CompositePKAggregateTests(TestCase):  
    3232        cls.comment_5 = Comment.objects.create(id=5, user=cls.user_3, text="barbaz")
    3333        cls.comment_6 = Comment.objects.create(id=6, user=cls.user_3, text="baz")
    3434
     35    def test_max_pk(self):
     36        # Could raise TypeError instead.
     37        self.assertEqual(Comment.objects.aggregate(Max("pk")), {'pk__max': 1})
     38
    3539    def test_users_annotated_with_comments_id_count(self):
    3640        user_1, user_2, user_3 = User.objects.annotate(Count("comments__id")).order_by(
    3741            "pk"

Relatedly, most of the built-in aggregate functions should set arity=1, which I'll include in a separate commit, but we can also discuss whether that needs to go through a deprecation path.

Change History (2)

comment:1 by Jacob Walls, 3 days ago

Has patch: set

comment:2 by Tim Graham, 2 days ago

Triage Stage: UnreviewedAccepted
Note: See TracTickets for help on using tickets.
Back to Top