1

My model:

from django.contrib.postgres.fields import JSONField

class Image(models.Model):
    tags = JSONField(null=False, blank=True, default={})

tags field value can be empty, or something like:

[
   {"tag": "xxx"}, 
   {"tag": "yyy"},
   {"tag": "zzz"}
]

The number or dicts may vary (from 0 to N).

I need to make a query that counts Images grouped by number of tags. Something like:

{
   "0": "345",
   "1": "1223",
   "2": "220",
   ...
   "N": "23"
}

where the key is the number of tags, and the value is the count of Image objects that contains this number of tags.

How can i do that? Thank you for your help!

UPDATE

I modified my code: now I don't use JsonField, but a dedicated model:

class ImageTag(models.Model):
    image = models.ForeignKey(Image)
    tag = models.CharField()

The question is the same :)

3
  • I don't think it's possible using the high level ORM API. However you should be able to build something with either extra() or raw querysets and the ideas from this question. Commented Aug 30, 2017 at 8:02
  • Also, you probably should read PostgreSQL anti-pattern: unnecessary json columns. Most notably, “PostgreSQL has json support but you shouldn’t use it for the great majority of what you’re doing […] as it’ll make querying and manipulating it harder.” Commented Aug 30, 2017 at 8:03
  • I expose a subset of information I store in this jsonfield; thank you always for the interesting read :) Commented Aug 30, 2017 at 8:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.