Return a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, evaluate the entire QuerySet.
(self, id_list=None, *, field_name="pk")
| 1206 | return await sync_to_async(self.last)() |
| 1207 | |
| 1208 | def in_bulk(self, id_list=None, *, field_name="pk"): |
| 1209 | """ |
| 1210 | Return a dictionary mapping each of the given IDs to the object with |
| 1211 | that ID. If `id_list` isn't provided, evaluate the entire QuerySet. |
| 1212 | """ |
| 1213 | if self.query.is_sliced: |
| 1214 | raise TypeError("Cannot use 'limit' or 'offset' with in_bulk().") |
| 1215 | if id_list is not None and not id_list: |
| 1216 | return {} |
| 1217 | opts = self.model._meta |
| 1218 | unique_fields = [ |
| 1219 | constraint.fields[0] |
| 1220 | for constraint in opts.total_unique_constraints |
| 1221 | if len(constraint.fields) == 1 |
| 1222 | ] |
| 1223 | if ( |
| 1224 | field_name != "pk" |
| 1225 | and not opts.get_field(field_name).unique |
| 1226 | and field_name not in unique_fields |
| 1227 | and self.query.distinct_fields != (field_name,) |
| 1228 | ): |
| 1229 | raise ValueError( |
| 1230 | "in_bulk()'s field_name must be a unique field but %r isn't." |
| 1231 | % field_name |
| 1232 | ) |
| 1233 | |
| 1234 | qs = self |
| 1235 | |
| 1236 | def get_obj(obj): |
| 1237 | return obj |
| 1238 | |
| 1239 | if issubclass(self._iterable_class, ModelIterable): |
| 1240 | # Raise an AttributeError if field_name is deferred. |
| 1241 | get_key = operator.attrgetter(field_name) |
| 1242 | |
| 1243 | elif issubclass(self._iterable_class, ValuesIterable): |
| 1244 | if field_name not in self.query.values_select: |
| 1245 | qs = qs.values(field_name, *self.query.values_select) |
| 1246 | |
| 1247 | def get_obj(obj): # noqa: F811 |
| 1248 | # We can safely mutate the dictionaries returned by |
| 1249 | # ValuesIterable here, since they are limited to the scope |
| 1250 | # of this function, and get_key runs before get_obj. |
| 1251 | del obj[field_name] |
| 1252 | return obj |
| 1253 | |
| 1254 | get_key = operator.itemgetter(field_name) |
| 1255 | |
| 1256 | elif issubclass(self._iterable_class, ValuesListIterable): |
| 1257 | try: |
| 1258 | field_index = self.query.values_select.index(field_name) |
| 1259 | except ValueError: |
| 1260 | # field_name is missing from values_select, so add it. |
| 1261 | field_index = 0 |
| 1262 | if issubclass(self._iterable_class, NamedValuesListIterable): |
| 1263 | kwargs = {"named": True} |
| 1264 | else: |
| 1265 | kwargs = {} |