﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
36326	Add support for CompositePrimaryKey in QuerySet.raw()	Adam Johnson	JaeHyuckSa	"Currently, a check in `RawModelIterable` fails for models with a `CompositePrimaryKey`.

For example, this model:

{{{#!python
class AuthorEvent(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    pk = models.CompositePrimaryKey(
        ""author"",
        ""timestamp"",
    )
}}}

fails like:

{{{
In [2]: list(AuthorEvent.objects.raw(""SELECT * FROM example_authorevent""))
---------------------------------------------------------------------------
FieldDoesNotExist                         Traceback (most recent call last)
Cell In[2], line 1
----> 1 list(AuthorEvent.objects.raw(""SELECT * FROM example_authorevent""))

File ..../django/db/models/query.py:2133, in RawQuerySet.__iter__(self)
   2132 def __iter__(self):
-> 2133     self._fetch_all()
   2134     return iter(self._result_cache)

File ..../django/db/models/query.py:2120, in RawQuerySet._fetch_all(self)
   2118 def _fetch_all(self):
   2119     if self._result_cache is None:
-> 2120         self._result_cache = list(self.iterator())
   2121     if self._prefetch_related_lookups and not self._prefetch_done:
   2122         self._prefetch_related_objects()

File ..../django/db/models/query.py:2147, in RawQuerySet.iterator(self)
   2146 def iterator(self):
-> 2147     yield from RawModelIterable(self)

File ..../django/db/models/query.py:169, in RawModelIterable.__iter__(self)
    167 model_cls = self.queryset.model
    168 if model_cls._meta.pk.attname not in model_init_names:
--> 169     raise exceptions.FieldDoesNotExist(
    170         ""Raw query must include the primary key""
    171     )
    172 fields = [self.queryset.model_fields.get(c) for c in self.queryset.columns]
    173 cols = [f.get_col(f.model._meta.db_table) if f else None for f in fields]

FieldDoesNotExist: Raw query must include the primary key
}}}

To add support, we should add a test, update this check to look for all columns in the PK, and fix anything else as necessary."	New feature	closed	Database layer (models, ORM)	dev	Normal	fixed		Csirmaz Bendegúz Simon Charette	Ready for checkin	1	0	0	0	1	0
