# Converting jsonb\_each postgresql query to Django ORM

**URL:** <https://forum.djangoproject.com/t/converting-jsonb-each-postgresql-query-to-django-orm/7424>\
**Category:** Using Django\
**Created:** [April 8, 2021, 9:52am UTC](https://forum.djangoproject.com/t/converting-jsonb-each-postgresql-query-to-django-orm/7424 "2021-04-08T09:52:22Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mtShaikh](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mtshaikh/32/4151_2.png) [@mtShaikh](https://forum.djangoproject.com/u/mtShaikh)\
**Post date:** [April 8, 2021, 9:52am UTC](https://forum.djangoproject.com/t/converting-jsonb-each-postgresql-query-to-django-orm/7424/1 "2021-04-08T09:52:22Z")

</div>

I have a query that joins on a jsonb type column in postgres that I want to convert to Django

```auto
SELECT anon_1.key AS tag, count(anon_1.value ->> 'polarity') AS count_1, anon_1.value ->> 'polarity' AS anon_2
FROM feedback f
         JOIN tagging t ON t.feedback_id = f.id
         JOIN jsonb_each(t.json_content -> 'entityMap') AS anon_3 ON true
         JOIN jsonb_each(((anon_3.value -> 'data') - 'selectionState') - 'segment') AS anon_1 ON true
where f.id = 2
GROUP BY anon_1.value ->> 'polarity', anon_1.key;

```

Following are my models:

```auto
class Tagging(BaseModel):
    class Meta:
        db_table = "tagging"

    json_content = models.JSONField(default=dict)
    feedback = models.ForeignKey("Feedback", models.CASCADE)

class Feedback(BaseModel):
    class Meta:
        db_table = "feedback"

    feedback_text = models.TextField(blank=True, null=True)

```

The json\_content field stores data in the following format:

```auto
{
  "entityMap":
  {
    "0":
    {
      "data":
      {
        "people":
        {
          "labelId": 5,
          "polarity": "positive"
        },
        "segment": "a small segment",
        "selectionState":
        {
          "focusKey": "9xrre",
          "hasFocus": true,
          "anchorKey": "9xrre",
          "isBackward": false,
          "focusOffset": 75,
          "anchorOffset": 3
        }
      },
      "type": "TAG",
      "mutability": "IMMUTABLE"
    },
    "1":
    {
      "data":
      {
        "product":
        {
          "labelId": 6,
          "polarity": "positive"
        },
        "segment": "another segment",
        "selectionState":
        {
          "focusKey": "9xrre",
          "hasFocus": true,
          "anchorKey": "9xrre",
          "isBackward": false,
          "focusOffset": 138,
          "anchorOffset": 79
        }
      },
      "type": "TAG",
      "mutability": "IMMUTABLE"
    }
  }
}

```

What I want is to get count of the polarities per tag. The tags are the keys of the `data` dict in the `json_content` field. I’m confused as to how to join the `tagging` table with the `jsonb_each` function in Django. Any help would be appreciated!
