Opened 4 years ago

Closed 4 years ago

#31691 closed New feature (fixed)

Added ordering support to JSONBAgg.

Reported by: john-parton Owned by: john-parton
Component: contrib.postgres 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 (last modified by john-parton)

Here's a contrived example:

class Author(models.Model):
    name = models.CharField(max_length=50)
    alias = models.CharField(max_length=50, null=True, blank=True)
    age = models.PositiveSmallIntegerField(default=30)


class Article(models.Model):
    authors = models.ManyToManyField(Author, related_name='articles')
    title = models.CharField(max_length=50)
    
    
Article.objects.annotate(
    authors_json=JSONBAgg(
        Func(
            Value('name'), 'name',
            Value('alias'), 'alias',
            function='jsonb_build_object'
        ),
        ordering='age'
    )
)

The ordering kwarg is ignored, but Postgres would have no problem understanding the aggregate with an ORDER BY clause

In my code I did the following

class OrderableJSONBAgg(OrderableAggMixin, Aggregate):
    function = 'JSONB_AGG'
    template = '%(function)s(%(expressions)s %(ordering)s)'
    output_field = JSONField()

    def convert_value(self, value, expression, connection):
        if not value:
            return []
        return value
    
    
from myapp.aggregates import OrderableJSONBAgg as JSONBAgg

I believe replacing the existing JSONBAgg with this implementation would add the feature, with no backwards compat issues.

I would be happy to submit a pull request.

Change History (8)

comment:1 by john-parton, 4 years ago

Description: modified (diff)

comment:2 by john-parton, 4 years ago

Description: modified (diff)

comment:3 by john-parton, 4 years ago

Description: modified (diff)

comment:4 by john-parton, 4 years ago

Description: modified (diff)

comment:5 by Mariusz Felisiak, 4 years ago

Component: Database layer (models, ORM)contrib.postgres
Summary: django.contrib.postgres.aggregates.JSONBAgg does not support orderingAdded ordering support to JSONBAgg.
Triage Stage: UnreviewedAccepted
Version: 3.0master

Would you like to prepare a patch? (see similar patch 96199e562dcc409ab4bdc2b2146fa7cf73c7c5fe for ArrayAgg and StringAgg).

comment:6 by john-parton, 4 years ago

Owner: changed from nobody to john-parton
Status: newassigned

Sure. I think I can handle it.

comment:7 by Simon Charette, 4 years ago

Has patch: set
Version 0, edited 4 years ago by Simon Charette (next)

comment:8 by Mariusz Felisiak <felisiak.mariusz@…>, 4 years ago

Resolution: fixed
Status: assignedclosed

In a8473b4d:

Fixed #31691 -- Added ordering support to JSONBAgg.

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