We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Unable to see lessons created after upgrading Kolibri with PostgreSQL
<!--
Instructions:
 * Fill out the sections below, replace …'s with information about your issue
 * Use the 'preview' function above this text box to verify formatting before submitting
-->

### Observed behavior
<!--
Description of the behavior that was observed, including screenshots or other references when applicable
-->

After upgrading Kolibri from 0.13.3 to 0.14.0b8, I'm unable to see the lessons, quizzes, class activities, and reports that I created before the upgrade on the Coach page. This issue only occurs when running Kolibri in PostgreSQL. In sqlite database, everything works fine.

### Expected behavior
<!--
Description of what behavior was expected but did not occur
-->

Users should be able to see lessons/quizzes they created previously after the version upgrade 

### User-facing consequences
<!--
Implications and real-world consequences for learners, coaches, admins, and other users of the application
-->

Users are unable to see the lessons and quizzes, although they exist in the database

### Errors and logs
<!--
Relevant logs from:
 * the command line
 * ~/.kolibri/logs/kolibri.txt
 * the browser console

Please wrap errors in triple backticks for clean formatting like this:
```
01:10 info: something happened
01:12 error: something bad happened
```
-->

Here's the error in the console:
<img width="1280" alt="Screen Shot 2020-07-08 at 2 08 15 PM" src="https://user-images.githubusercontent.com/19424916/86973443-6a550c80-c129-11ea-82ae-5a85c89802aa.png">

coach page after the upgrade:
<img width="1278" alt="Screen Shot 2020-07-08 at 2 27 29 PM" src="https://user-images.githubusercontent.com/19424916/86973539-9ec8c880-c129-11ea-9993-ba32efe90826.png">


### Steps to reproduce
<!--
Precise steps that someone else can follow in order to see this behavior
-->

1. start kolibri 0.13.3 in postgresql
2. create a class with a lesson and some class activity
3. upgrade kolibri to 0.14.0b8
4. check the coach page again

### Context
<!--
Tell us about your environment, including:
 * Kolibri version
 * Operating system
 * Browser
-->

Kolibri version: 0.14.0b8

Unable to see lessons created after upgrading Kolibri with PostgreSQL
<!--
Instructions:
 * Fill out the sections below, replace …'s with information about your issue
 * Use the 'preview' function above this text box to verify formatting before submitting
-->

### Observed behavior
<!--
Description of the behavior that was observed, including screenshots or other references when applicable
-->

After upgrading Kolibri from 0.13.3 to 0.14.0b8, I'm unable to see the lessons, quizzes, class activities, and reports that I created before the upgrade on the Coach page. This issue only occurs when running Kolibri in PostgreSQL. In sqlite database, everything works fine.

### Expected behavior
<!--
Description of what behavior was expected but did not occur
-->

Users should be able to see lessons/quizzes they created previously after the version upgrade 

### User-facing consequences
<!--
Implications and real-world consequences for learners, coaches, admins, and other users of the application
-->

Users are unable to see the lessons and quizzes, although they exist in the database

### Errors and logs
<!--
Relevant logs from:
 * the command line
 * ~/.kolibri/logs/kolibri.txt
 * the browser console

Please wrap errors in triple backticks for clean formatting like this:
```
01:10 info: something happened
01:12 error: something bad happened
```
-->

Here's the error in the console:
<img width="1280" alt="Screen Shot 2020-07-08 at 2 08 15 PM" src="https://user-images.githubusercontent.com/19424916/86973443-6a550c80-c129-11ea-82ae-5a85c89802aa.png">

coach page after the upgrade:
<img width="1278" alt="Screen Shot 2020-07-08 at 2 27 29 PM" src="https://user-images.githubusercontent.com/19424916/86973539-9ec8c880-c129-11ea-9993-ba32efe90826.png">


### Steps to reproduce
<!--
Precise steps that someone else can follow in order to see this behavior
-->

1. start kolibri 0.13.3 in postgresql
2. create a class with a lesson and some class activity
3. upgrade kolibri to 0.14.0b8
4. check the coach page again

### Context
<!--
Tell us about your environment, including:
 * Kolibri version
 * Operating system
 * Browser
-->

Kolibri version: 0.14.0b8


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kolibri/core/query.py`
Content:
```
1 from django.db import connection
2 from django.db.models import Aggregate
3 from django.db.models import CharField
4 from django.db.models import IntegerField
5 from django.db.models import Subquery
6 
7 try:
8     from django.contrib.postgres.aggregates import ArrayAgg
9 
10     class NotNullArrayAgg(ArrayAgg):
11         def __init__(self, *args, **kwargs):
12             self.result_field = kwargs.pop("result_field", None)
13             super(NotNullArrayAgg, self).__init__(*args, **kwargs)
14 
15         def convert_value(self, value, expression, connection, context):
16             if not value:
17                 return []
18             results = list(filter(lambda x: x is not None, value))
19             if self.result_field is not None:
20                 return list(map(self.result_field.to_python, results))
21             return results
22 
23 
24 except ImportError:
25     NotNullArrayAgg = None
26 
27 
28 class SQCount(Subquery):
29     # Include ALIAS at the end to support Postgres
30     template = "(SELECT COUNT(%(field)s) FROM (%(subquery)s) AS %(field)s__sum)"
31     output_field = IntegerField()
32 
33 
34 class SQSum(Subquery):
35     # Include ALIAS at the end to support Postgres
36     template = "(SELECT SUM(%(field)s) FROM (%(subquery)s) AS %(field)s__sum)"
37     output_field = IntegerField()
38 
39 
40 class GroupConcatSubquery(Subquery):
41     template = "(SELECT GROUP_CONCAT(%(field)s) FROM (%(subquery)s) AS %(field)s__sum)"
42     output_field = CharField()
43 
44     def as_postgresql(self, compiler, connection):
45         self.template = (
46             "(SELECT STRING_AGG(%(field)s, ',') FROM (%(subquery)s) AS %(field)s__sum)"
47         )
48         return super(GroupConcatSubquery, self).as_sql(compiler, connection)
49 
50 
51 class GroupConcat(Aggregate):
52     template = "GROUP_CONCAT(%(field)s)"
53     output_field = CharField()
54 
55     def __init__(self, *args, **kwargs):
56         self.result_field = kwargs.pop("result_field", None)
57         super(GroupConcat, self).__init__(*args, **kwargs)
58 
59     def convert_value(self, value, expression, connection, context):
60         if not value:
61             return []
62         results = value.split(",")
63         if self.result_field is not None:
64             return list(map(self.result_field.to_python, results))
65         return results
66 
67 
68 def get_source_field(model, field_path):
69     # Get the source field from the model so that we can properly coerce values
70     # this is necessary when we are using GroupConcat to return non-string fields.
71     paths = field_path.split("__")
72     while len(paths) > 1:
73         model = model._meta.get_field(paths.pop(0)).related_model
74     return model._meta.get_field(paths[0])
75 
76 
77 def annotate_array_aggregate(queryset, **kwargs):
78     model = queryset.model
79     if connection.vendor == "postgresql" and NotNullArrayAgg is not None:
80         return queryset.annotate(
81             **{
82                 target: NotNullArrayAgg(
83                     source, result_field=get_source_field(model, source)
84                 )
85                 for target, source in kwargs.items()
86             }
87         )
88     # Call values on "pk" to insert a GROUP BY to ensure the GROUP CONCAT
89     # is called by row and not across the entire queryset.
90     return queryset.values("pk").annotate(
91         **{
92             target: GroupConcat(source, result_field=get_source_field(model, source))
93             for target, source in kwargs.items()
94         }
95     )
96
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/kolibri/core/query.py b/kolibri/core/query.py
--- a/kolibri/core/query.py
+++ b/kolibri/core/query.py
@@ -71,7 +71,10 @@
     paths = field_path.split("__")
     while len(paths) > 1:
         model = model._meta.get_field(paths.pop(0)).related_model
-    return model._meta.get_field(paths[0])
+    field = model._meta.get_field(paths[0])
+    if field.is_relation and field.foreign_related_fields:
+        field = field.foreign_related_fields[0]
+    return field
 
 
 def annotate_array_aggregate(queryset, **kwargs):

{"golden_diff": "diff --git a/kolibri/core/query.py b/kolibri/core/query.py\n--- a/kolibri/core/query.py\n+++ b/kolibri/core/query.py\n@@ -71,7 +71,10 @@\n     paths = field_path.split(\"__\")\n     while len(paths) > 1:\n         model = model._meta.get_field(paths.pop(0)).related_model\n-    return model._meta.get_field(paths[0])\n+    field = model._meta.get_field(paths[0])\n+    if field.is_relation and field.foreign_related_fields:\n+        field = field.foreign_related_fields[0]\n+    return field\n \n \n def annotate_array_aggregate(queryset, **kwargs):\n", "issue": "Unable to see lessons created after upgrading Kolibri with PostgreSQL\n<!--\r\nInstructions:\r\n * Fill out the sections below, replace \u2026's with information about your issue\r\n * Use the 'preview' function above this text box to verify formatting before submitting\r\n-->\r\n\r\n### Observed behavior\r\n<!--\r\nDescription of the behavior that was observed, including screenshots or other references when applicable\r\n-->\r\n\r\nAfter upgrading Kolibri from 0.13.3 to 0.14.0b8, I'm unable to see the lessons, quizzes, class activities, and reports that I created before the upgrade on the Coach page. This issue only occurs when running Kolibri in PostgreSQL. In sqlite database, everything works fine.\r\n\r\n### Expected behavior\r\n<!--\r\nDescription of what behavior was expected but did not occur\r\n-->\r\n\r\nUsers should be able to see lessons/quizzes they created previously after the version upgrade \r\n\r\n### User-facing consequences\r\n<!--\r\nImplications and real-world consequences for learners, coaches, admins, and other users of the application\r\n-->\r\n\r\nUsers are unable to see the lessons and quizzes, although they exist in the database\r\n\r\n### Errors and logs\r\n<!--\r\nRelevant logs from:\r\n * the command line\r\n * ~/.kolibri/logs/kolibri.txt\r\n * the browser console\r\n\r\nPlease wrap errors in triple backticks for clean formatting like this:\r\n```\r\n01:10 info: something happened\r\n01:12 error: something bad happened\r\n```\r\n-->\r\n\r\nHere's the error in the console:\r\n<img width=\"1280\" alt=\"Screen Shot 2020-07-08 at 2 08 15 PM\" src=\"https://user-images.githubusercontent.com/19424916/86973443-6a550c80-c129-11ea-82ae-5a85c89802aa.png\">\r\n\r\ncoach page after the upgrade:\r\n<img width=\"1278\" alt=\"Screen Shot 2020-07-08 at 2 27 29 PM\" src=\"https://user-images.githubusercontent.com/19424916/86973539-9ec8c880-c129-11ea-9993-ba32efe90826.png\">\r\n\r\n\r\n### Steps to reproduce\r\n<!--\r\nPrecise steps that someone else can follow in order to see this behavior\r\n-->\r\n\r\n1. start kolibri 0.13.3 in postgresql\r\n2. create a class with a lesson and some class activity\r\n3. upgrade kolibri to 0.14.0b8\r\n4. check the coach page again\r\n\r\n### Context\r\n<!--\r\nTell us about your environment, including:\r\n * Kolibri version\r\n * Operating system\r\n * Browser\r\n-->\r\n\r\nKolibri version: 0.14.0b8\r\n\nUnable to see lessons created after upgrading Kolibri with PostgreSQL\n<!--\r\nInstructions:\r\n * Fill out the sections below, replace \u2026's with information about your issue\r\n * Use the 'preview' function above this text box to verify formatting before submitting\r\n-->\r\n\r\n### Observed behavior\r\n<!--\r\nDescription of the behavior that was observed, including screenshots or other references when applicable\r\n-->\r\n\r\nAfter upgrading Kolibri from 0.13.3 to 0.14.0b8, I'm unable to see the lessons, quizzes, class activities, and reports that I created before the upgrade on the Coach page. This issue only occurs when running Kolibri in PostgreSQL. In sqlite database, everything works fine.\r\n\r\n### Expected behavior\r\n<!--\r\nDescription of what behavior was expected but did not occur\r\n-->\r\n\r\nUsers should be able to see lessons/quizzes they created previously after the version upgrade \r\n\r\n### User-facing consequences\r\n<!--\r\nImplications and real-world consequences for learners, coaches, admins, and other users of the application\r\n-->\r\n\r\nUsers are unable to see the lessons and quizzes, although they exist in the database\r\n\r\n### Errors and logs\r\n<!--\r\nRelevant logs from:\r\n * the command line\r\n * ~/.kolibri/logs/kolibri.txt\r\n * the browser console\r\n\r\nPlease wrap errors in triple backticks for clean formatting like this:\r\n```\r\n01:10 info: something happened\r\n01:12 error: something bad happened\r\n```\r\n-->\r\n\r\nHere's the error in the console:\r\n<img width=\"1280\" alt=\"Screen Shot 2020-07-08 at 2 08 15 PM\" src=\"https://user-images.githubusercontent.com/19424916/86973443-6a550c80-c129-11ea-82ae-5a85c89802aa.png\">\r\n\r\ncoach page after the upgrade:\r\n<img width=\"1278\" alt=\"Screen Shot 2020-07-08 at 2 27 29 PM\" src=\"https://user-images.githubusercontent.com/19424916/86973539-9ec8c880-c129-11ea-9993-ba32efe90826.png\">\r\n\r\n\r\n### Steps to reproduce\r\n<!--\r\nPrecise steps that someone else can follow in order to see this behavior\r\n-->\r\n\r\n1. start kolibri 0.13.3 in postgresql\r\n2. create a class with a lesson and some class activity\r\n3. upgrade kolibri to 0.14.0b8\r\n4. check the coach page again\r\n\r\n### Context\r\n<!--\r\nTell us about your environment, including:\r\n * Kolibri version\r\n * Operating system\r\n * Browser\r\n-->\r\n\r\nKolibri version: 0.14.0b8\r\n\n", "before_files": [{"content": "from django.db import connection\nfrom django.db.models import Aggregate\nfrom django.db.models import CharField\nfrom django.db.models import IntegerField\nfrom django.db.models import Subquery\n\ntry:\n    from django.contrib.postgres.aggregates import ArrayAgg\n\n    class NotNullArrayAgg(ArrayAgg):\n        def __init__(self, *args, **kwargs):\n            self.result_field = kwargs.pop(\"result_field\", None)\n            super(NotNullArrayAgg, self).__init__(*args, **kwargs)\n\n        def convert_value(self, value, expression, connection, context):\n            if not value:\n                return []\n            results = list(filter(lambda x: x is not None, value))\n            if self.result_field is not None:\n                return list(map(self.result_field.to_python, results))\n            return results\n\n\nexcept ImportError:\n    NotNullArrayAgg = None\n\n\nclass SQCount(Subquery):\n    # Include ALIAS at the end to support Postgres\n    template = \"(SELECT COUNT(%(field)s) FROM (%(subquery)s) AS %(field)s__sum)\"\n    output_field = IntegerField()\n\n\nclass SQSum(Subquery):\n    # Include ALIAS at the end to support Postgres\n    template = \"(SELECT SUM(%(field)s) FROM (%(subquery)s) AS %(field)s__sum)\"\n    output_field = IntegerField()\n\n\nclass GroupConcatSubquery(Subquery):\n    template = \"(SELECT GROUP_CONCAT(%(field)s) FROM (%(subquery)s) AS %(field)s__sum)\"\n    output_field = CharField()\n\n    def as_postgresql(self, compiler, connection):\n        self.template = (\n            \"(SELECT STRING_AGG(%(field)s, ',') FROM (%(subquery)s) AS %(field)s__sum)\"\n        )\n        return super(GroupConcatSubquery, self).as_sql(compiler, connection)\n\n\nclass GroupConcat(Aggregate):\n    template = \"GROUP_CONCAT(%(field)s)\"\n    output_field = CharField()\n\n    def __init__(self, *args, **kwargs):\n        self.result_field = kwargs.pop(\"result_field\", None)\n        super(GroupConcat, self).__init__(*args, **kwargs)\n\n    def convert_value(self, value, expression, connection, context):\n        if not value:\n            return []\n        results = value.split(\",\")\n        if self.result_field is not None:\n            return list(map(self.result_field.to_python, results))\n        return results\n\n\ndef get_source_field(model, field_path):\n    # Get the source field from the model so that we can properly coerce values\n    # this is necessary when we are using GroupConcat to return non-string fields.\n    paths = field_path.split(\"__\")\n    while len(paths) > 1:\n        model = model._meta.get_field(paths.pop(0)).related_model\n    return model._meta.get_field(paths[0])\n\n\ndef annotate_array_aggregate(queryset, **kwargs):\n    model = queryset.model\n    if connection.vendor == \"postgresql\" and NotNullArrayAgg is not None:\n        return queryset.annotate(\n            **{\n                target: NotNullArrayAgg(\n                    source, result_field=get_source_field(model, source)\n                )\n                for target, source in kwargs.items()\n            }\n        )\n    # Call values on \"pk\" to insert a GROUP BY to ensure the GROUP CONCAT\n    # is called by row and not across the entire queryset.\n    return queryset.values(\"pk\").annotate(\n        **{\n            target: GroupConcat(source, result_field=get_source_field(model, source))\n            for target, source in kwargs.items()\n        }\n    )\n", "path": "kolibri/core/query.py"}], "after_files": [{"content": "from django.db import connection\nfrom django.db.models import Aggregate\nfrom django.db.models import CharField\nfrom django.db.models import IntegerField\nfrom django.db.models import Subquery\n\ntry:\n    from django.contrib.postgres.aggregates import ArrayAgg\n\n    class NotNullArrayAgg(ArrayAgg):\n        def __init__(self, *args, **kwargs):\n            self.result_field = kwargs.pop(\"result_field\", None)\n            super(NotNullArrayAgg, self).__init__(*args, **kwargs)\n\n        def convert_value(self, value, expression, connection, context):\n            if not value:\n                return []\n            results = list(filter(lambda x: x is not None, value))\n            if self.result_field is not None:\n                return list(map(self.result_field.to_python, results))\n            return results\n\n\nexcept ImportError:\n    NotNullArrayAgg = None\n\n\nclass SQCount(Subquery):\n    # Include ALIAS at the end to support Postgres\n    template = \"(SELECT COUNT(%(field)s) FROM (%(subquery)s) AS %(field)s__sum)\"\n    output_field = IntegerField()\n\n\nclass SQSum(Subquery):\n    # Include ALIAS at the end to support Postgres\n    template = \"(SELECT SUM(%(field)s) FROM (%(subquery)s) AS %(field)s__sum)\"\n    output_field = IntegerField()\n\n\nclass GroupConcatSubquery(Subquery):\n    template = \"(SELECT GROUP_CONCAT(%(field)s) FROM (%(subquery)s) AS %(field)s__sum)\"\n    output_field = CharField()\n\n    def as_postgresql(self, compiler, connection):\n        self.template = (\n            \"(SELECT STRING_AGG(%(field)s, ',') FROM (%(subquery)s) AS %(field)s__sum)\"\n        )\n        return super(GroupConcatSubquery, self).as_sql(compiler, connection)\n\n\nclass GroupConcat(Aggregate):\n    template = \"GROUP_CONCAT(%(field)s)\"\n    output_field = CharField()\n\n    def __init__(self, *args, **kwargs):\n        self.result_field = kwargs.pop(\"result_field\", None)\n        super(GroupConcat, self).__init__(*args, **kwargs)\n\n    def convert_value(self, value, expression, connection, context):\n        if not value:\n            return []\n        results = value.split(\",\")\n        if self.result_field is not None:\n            return list(map(self.result_field.to_python, results))\n        return results\n\n\ndef get_source_field(model, field_path):\n    # Get the source field from the model so that we can properly coerce values\n    # this is necessary when we are using GroupConcat to return non-string fields.\n    paths = field_path.split(\"__\")\n    while len(paths) > 1:\n        model = model._meta.get_field(paths.pop(0)).related_model\n    field = model._meta.get_field(paths[0])\n    if field.is_relation and field.foreign_related_fields:\n        field = field.foreign_related_fields[0]\n    return field\n\n\ndef annotate_array_aggregate(queryset, **kwargs):\n    model = queryset.model\n    if connection.vendor == \"postgresql\" and NotNullArrayAgg is not None:\n        return queryset.annotate(\n            **{\n                target: NotNullArrayAgg(\n                    source, result_field=get_source_field(model, source)\n                )\n                for target, source in kwargs.items()\n            }\n        )\n    # Call values on \"pk\" to insert a GROUP BY to ensure the GROUP CONCAT\n    # is called by row and not across the entire queryset.\n    return queryset.values(\"pk\").annotate(\n        **{\n            target: GroupConcat(source, result_field=get_source_field(model, source))\n            for target, source in kwargs.items()\n        }\n    )\n", "path": "kolibri/core/query.py"}]}