Skip to content

models with ID columns not named ID cause exception #29

@FalseProtagonist

Description

@FalseProtagonist

With a model that has an ID column not named ID, and the following code:

class TestView(PandasView):
    queryset = WeirdIDModel.objects.all()
    serializer_class = WeirdIDModelSerializer

when trying to query the class, you get an error KeyError, "id".

Reading that stack trace and the source I see that this is because by default we run "set_index('id') on the df, and this can be fixed in three obvious ways:

  1. set pandas_index on the meta of the serializer
  2. override get_index_fields on the serializer
  3. override get_dataframe
  1. setting the index seems to be needless duplication (I've already written once what the index of this model is)
  2. an override to get_index_fields I think would just create behaviour that should be default:
    WeirdIDModelSerializer._meta.pk.name gives the ID, for my version of Django at least

so something like

try:
    id_name = (self.<field for model>)._meta.pk.name
except:
    id_name = 'id'
default_fields = [id_name]
  1. Thinking about it more, and reading the source, it seems odd to even set an index, especially without preserving the original column - I think that DRF classes that we're mimicking would by default pass the index through to the client, and since I'm trying to drop-in replace some existing code which might rely on that, I'll have to replicate that manually.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions