{"id":34046127,"url":"https://github.com/zxibizz/django-raw-sugar","last_synced_at":"2026-04-07T04:31:59.413Z","repository":{"id":42899179,"uuid":"313079726","full_name":"zxibizz/django-raw-sugar","owner":"zxibizz","description":"Turns your raw sql into a QuerySet.","archived":false,"fork":false,"pushed_at":"2022-03-26T10:58:46.000Z","size":63,"stargazers_count":52,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-12-15T17:06:53.281Z","etag":null,"topics":["django","django-models"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zxibizz.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-11-15T17:00:23.000Z","updated_at":"2024-10-04T13:50:52.000Z","dependencies_parsed_at":"2022-09-26T16:22:36.389Z","dependency_job_id":null,"html_url":"https://github.com/zxibizz/django-raw-sugar","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/zxibizz/django-raw-sugar","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zxibizz%2Fdjango-raw-sugar","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zxibizz%2Fdjango-raw-sugar/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zxibizz%2Fdjango-raw-sugar/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zxibizz%2Fdjango-raw-sugar/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zxibizz","download_url":"https://codeload.github.com/zxibizz/django-raw-sugar/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zxibizz%2Fdjango-raw-sugar/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31500397,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-07T03:10:19.677Z","status":"ssl_error","status_checked_at":"2026-04-07T03:10:13.982Z","response_time":105,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","django-models"],"created_at":"2025-12-13T23:36:41.704Z","updated_at":"2026-04-07T04:31:59.393Z","avatar_url":"https://github.com/zxibizz.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# django-raw-sugar\n\nTurns your raw sql into a QuerySet.\n\n## Installation\n\nInstall using `pip`...\n\n    pip install django-raw-sugar\n\n## How to use\n### Basic usage\nAttach `RawManager` instance to your model. Then use it's `.from_raw()` method.\n\n    RawManager.from_raw(raw_query=None, params=None, translations=None, null_fields=None, db_table=None)\n\nYou should provide either `raw_query` or `db_table` (but not both).\n\n```python\n# models.py\nfrom django.db import models\nfrom raw_sugar import RawManager\n\nclass MySimpleModel(models.Model):\n    name = models.TextField()\n    number = models.IntegerField()\n    source = models.ForeignKey(AnotherSimpleModel, models.DO_NOTHING)\n\n    objects = RawManager()\n\n# some other file\nfrom .models import MySimpleModel\n\nqueryset = MySimpleModel.objects.from_raw(\n    'SELECT Null as id, \"my str\" as name, 111 as number, Null as source_id')\n```\n\nThe result of your raw sql must contain all the fields that are present in target model, including primary key and foreign keys. If you know your raw sql lacks some fields, you can provide the `null_fields` argument instead of modifying your query:\n\n```python\nqueryset = MySimpleModel.objects.from_raw(\n    'SELECT \"my str\" as name, 111 as number', null_fields=['id', 'source_id'])\n```\n\nThe resulting queryset is a regular `models.QuerySet` instance, and can be handled accordingly:\n\n```python\nqueryset = queryset.filter(number__gte=10)\\\n    .exclude(number__gte=1000)\\\n    .filter(name__contains='s')\\\n    .order_by('number')\\\n    .select_related('source')\nprint(queryset[0].name) # \"my str\"\n```\n\n### Passing parameters\nIf you need to perform parameterized queries, you can use the `params` argument:\n```python\nqueryset = MySimpleModel.objects.from_raw(\n    'SELECT \"%s\" as name, 111 as number', \n    params=['my str'],\n    null_fields=['id', 'source_id'])\n```\nIf you want to pass params deferred, you can use the `with_params` method:\n```python\nqueryset = MySimpleModel.objects.from_raw(\n    'SELECT \"%s\" as name, 111 as number', \n    null_fields=['id', 'source_id'])\nqueryset = queryset.with_params('my str')\n```\n\n### Using translations\nIf the field names of queried table differ from the model field names, you can map fields by using the `translations` argument:\n```python\nqueryset = MySimpleModel.objects.from_raw(\n    'SELECT \"%s\" as name, 111 as inner_number', \n    params=['my str'],\n    translations={'inner_number': 'number'},\n    null_fields=['id', 'source_id'])\n```\n\n### Pre defined source raw sql\nYou can define a model manager that uses your raw sql as query source by default. You can do this by passing a `from_raw` argument to RawManager, or by using the `raw_manager` decorator to method that returns a `FromRaw` instance:\n\n```python\nfrom django.db import models\nfrom raw_sugar import raw_manager, RawManager, FromRaw\n\nclass MySimpleModel(models.model):\n    name = models.TextField()\n    number = models.IntegerField()\n    source = models.ForeignKey(AnotherSimpleModel, models.DO_NOTHING)\n\n    my_raw_manager = RawManager(FromRaw('SELECT \"my str\" as name, 111 as number',\n                                        null_fields=['id', 'source_id']))\n\n    @raw_manager\n    def my_raw_manager_2(cls):\n        return FromRaw('SELECT \"my str\" as name, 111 as number',\n                       null_fields=['id', 'source_id'])\n\n    @raw_manager(is_callable=True)\n    def my_callable_raw_manager(cls, name=\"\"):\n        return FromRaw('SELECT %s as name, 111 as number',\n                       null_fields=['id', 'source_id'],\n                       params=[name])\n\n# some other file\nfrom .models import MySimpleModel\n\nqueryset = MySimpleModel.my_raw_source.all()\nqueryset = MySimpleModel.my_raw_source_2.all()\nqueryset = MySimpleModel.my_callable_raw_source('my str').all()\n\nprint(queryset[0].name) # \"my str\"\n```\nThe `FromRaw` class accepts all the arguments as the `RawManager.from_raw`:\n    FromRaw(raw_query=None, params=None, translations=None, null_fields=None, db_table=None)\n\nWhen you use the `raw_manager` decorator, the parameters you pass to `with_params` method will be passed into the decorated method, not into your raw. If you need this behavour, you can do it manually:\n\n```python\n@raw_manager(is_callable=True)\ndef my_callable_raw_manager(cls, *args):\n    assert len(args) == 2\n    return FromRaw('SELECT %s as name, %s as number', null_fields=['id', 'source_id'], params=args)\n```\n\n### Querying views / table functions\nIf you have a sql view or a sql table function in your database and want to query it, instead of passing sql like `SELECT * from my_view` you can use the `db_table` argument:\n```python\nqueryset = MySimpleModel.objects.from_raw(db_table='my_view')\nqueryset = MySimpleModel.objects.from_raw(db_table='my_func(%s, %s)', params=['param', 1])\nqueryset = MySimpleModel.objects.from_raw(db_table='my_func(%s, %s)').with_params('param', 1)\n```\n\n### Use a QuerySet as a source\nYou can use a QuerySet instance as a source instead of raw sql by returning a `FromQuerySet` instance from decorated manager method:\n\n```python\nclass MySimpleModel(models.Model):\n    name = models.TextField()\n    number = models.IntegerField()\n    source = models.ForeignKey(\n        AnotherSimpleModel, models.DO_NOTHING, null=True)\n\n    @raw_manager\n    def my_qs_manager(cls):\n        return FromQuerySet(\n            cls.objects.values('source')\\\n                .annotate(_number=models.Sum('number')),\n            translations={'_number': 'number'})\n```\n\nThe `FromQuerySet` class accepts only a QuerySet and translations:\n\n    FromQuerySet(queryset, translations=None)\n\nIf the provided QuerySet lacks some fields, the `Null` will be returned. You don't need to specify `null_fields` as you would with the `FromRaw`.\n\n## Differences with `Manager.raw()`\nPros:\n - The result of executing of your raw sql is a **QuerySet** (!!!), and can filter, order, annotate, union, etc. it.\n\nCons:\n - The result of your `FromRaw` must contain all fields of target model, including primary and foreign keys. If you omit any, you get an `OperationalError('no such column: ...')` exception.\n - If you don't provide some fields in source QuerySet when use the `FromQuerySet`, this fields are filled with `Null`, and can not be loaded on demand. The Django's `RawQuerySet` [allows it](https://docs.djangoproject.com/en/3.1/topics/db/sql/#deferring-model-fields).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzxibizz%2Fdjango-raw-sugar","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzxibizz%2Fdjango-raw-sugar","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzxibizz%2Fdjango-raw-sugar/lists"}