{"record":{"id":"ecf7ba868afab3b7","repo":"django/django","slug":"foreignkey-mapping-must-be-of-dictionary-type","errorCode":null,"errorMessage":"ForeignKey mapping must be of dictionary type.","messagePattern":"ForeignKey mapping must be of dictionary type\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"django/contrib/gis/utils/layermapping.py","lineNumber":288,"sourceCode":"                self.geom_field = field_name\n                self.coord_dim = coord_dim\n                fields_val = model_field\n            elif isinstance(model_field, models.ForeignKey):\n                if isinstance(ogr_name, dict):\n                    # Is every given related model mapping field in the Layer?\n                    rel_model = model_field.remote_field.model\n                    for rel_name, ogr_field in ogr_name.items():\n                        idx = check_ogr_fld(ogr_field)\n                        try:\n                            rel_model._meta.get_field(rel_name)\n                        except FieldDoesNotExist:\n                            raise LayerMapError(\n                                'ForeignKey mapping field \"%s\" not in %s fields.'\n                                % (rel_name, rel_model.__class__.__name__)\n                            )\n                    fields_val = rel_model\n                else:\n                    raise TypeError(\"ForeignKey mapping must be of dictionary type.\")\n            else:\n                # Is the model field type supported by LayerMapping?\n                if model_field.__class__ not in self.FIELD_TYPES:\n                    raise LayerMapError(\n                        'Django field type \"%s\" has no OGR mapping (yet).' % fld_name\n                    )\n\n                # Is the OGR field in the Layer?\n                idx = check_ogr_fld(ogr_name)\n                ogr_field = ogr_field_types[idx]\n\n                # Can the OGR field type be mapped to the Django field type?\n                if not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__]):\n                    raise LayerMapError(\n                        'OGR field \"%s\" (of type %s) cannot be mapped to Django %s.'\n                        % (ogr_field, ogr_field.__name__, fld_name)\n                    )\n                fields_val = model_field","sourceCodeStart":270,"sourceCodeEnd":306,"githubUrl":"https://github.com/django/django/blob/ae25a40be07e8a749edf526df37c93e59d4a22c9/django/contrib/gis/utils/layermapping.py#L270-L306","documentation":"TypeError raised when a ForeignKey model field's mapping value is not a dict. LayerMapping requires ForeignKey mappings to be dictionaries mapping related-model field names to OGR column names so it can look up the related object.","triggerScenarios":"Passing mapping = {'city': 'CITY_NAME'} (string) for a ForeignKey instead of {'city': {'name': 'CITY_NAME'}}; passing a list or a single OGR column name where the FK dict is required.","commonSituations":"Misreading the LayerMapping docs; assuming FK mapping uses the same string form as scalar fields; auto-generating mappings from introspection that skip FK handling.","solutions":["Provide the FK mapping as a dict: {related_field_name: ogr_column_name}.","Confirm the model field is actually a ForeignKey (so the dict form is expected).","If you intended a plain field reference, change the model field to a non-FK type."],"exampleFix":"# before\nmapping = {'city': 'CITY_NAME'}  # TypeError\n\n# after\nmapping = {'city': {'name': 'CITY_NAME'}}","handlingStrategy":"type-guard","validationCode":"from django.db import models\n\ndef validate_fk_mapping_shape(model, mapping):\n    for k, v in mapping.items():\n        try:\n            f = model._meta.get_field(k)\n        except Exception:\n            continue\n        if isinstance(f, models.ForeignKey) and not isinstance(v, dict):\n            return f'{k} FK mapping must be a dict'\n    return None","typeGuard":"from django.db import models\n\ndef fk_mappings_are_dicts(model, mapping):\n    for k, v in mapping.items():\n        try:\n            f = model._meta.get_field(k)\n        except Exception:\n            continue\n        if isinstance(f, models.ForeignKey) and not isinstance(v, dict):\n            return False\n    return True","tryCatchPattern":"try:\n    LayerMapping(Model, path, mapping)\nexcept TypeError as e:\n    if 'must be of dictionary type' in str(e):\n        # wrap the value in a dict {rel_field: ogr_col}\n        ...","preventionTips":["Always format ForeignKey entries as {rel_field_name: ogr_column}.","Add a pre-flight assertion that every FK mapping value is a dict.","Document the FK mapping shape alongside your mapping examples."],"tags":["django","gis","layermapping","foreignkey","type-error"],"analyzedSha":"ae25a40be07e8a749edf526df37c93e59d4a22c9","analyzedAt":"2026-08-06T21:46:51.801Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}