Opened 12 months ago

Closed 12 months ago

Last modified 12 months ago

#35093 closed New feature (wontfix)

Allow SQL injection characters in QuerySet.annotate() aliases

Reported by: Eyal Segal Owned by: nobody
Component: Database layer (models, ORM) Version: 3.2
Severity: Normal Keywords: ORM, annotations
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Eyal Segal)

Encountered a limitation in Django ORM when using annotations with column aliases containing special characters like apostrophes or spaces. For example:

Model.objects.annotate(**{"VALUE_WITH_APOSTROPHE'-2": Count('attribute_name')})

This generates a ValueError: Column aliases cannot contain whitespace characters, quotation marks, semicolons, or SQL comments. While SQL syntax allows such value for fields, Django ORM does not, leading to a lack of flexibility and unexpected errors in ORM interactions.

Impact:

  • Causes flow errors during higher-level ORM interactions.
  • Limits application of ORM to real-world naming use cases.
  • Decreases reliability and user experience when special characters are present.

Proposed Solution:
Enhance the ORM's handling of annotate aliases to allow common special characters, aligning with real-world naming scenarios. Options could include:

  • Automatically transforming aliases before passing to SQL.
  • Configurable rules for "safe" special characters at the ORM level.

Interested in community and maintainers' perspectives on potential solutions to provide ORM-level flexibility for end-user applications. Looking forward to contributing to the discussion and development of this feature.

Change History (2)

comment:1 by Tim Graham, 12 months ago

Description: modified (diff)
Resolution: wontfix
Status: newclosed
Summary: Handling Special Characters in ORM Annotate AliasesAllow SQL injection characters in QuerySet.annotate() aliases

Did you look into why the restriction was added? (to prevent SQL injection: 93cae5cb2f9a4ef1514cf1a41f714fef08005200)

Something like .annotate(**{"VALUE_WITH_APOSTROPHE'-2": Count('attribute_name')}, allow_sql_injecdtion=True) is probably not going to fly. Feel free to make a proposal on the DevelopersMailingList if you want to start a discussion.

comment:2 by Eyal Segal, 12 months ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top