django-rest-framework-csv icon indicating copy to clipboard operation
django-rest-framework-csv copied to clipboard

Column names from verbose names

Open aop opened this issue 11 years ago • 2 comments
trafficstars

Since Django provides Fields a verbose_name attribute, it would be nice if that could be specified as the column name. This messes up the flattening maybe though...

aop avatar Apr 09 '14 18:04 aop

Hey, yeah, this is a good idea. Using the model verbose names may be difficult though, since the data no longer has any connection to the models by the time it gets to the renderer.

More generally, it would be useful to be able to specify a mapping of column header overrides for the renderer. It wouldn't have to mess up the flattening. I don't have much time in the immediate future to look dive into this, but if you want to send a pull request, or just start a branch, I'll pop in as time permits.

mjumbewu avatar Apr 14 '14 03:04 mjumbewu

I know this is an old issue, but I used a workaround to tackle this:

  • Based on this: https://blog.pboehm.org/blog/2013/02/05/extracting-field-names-from-django-model-instance/ I wrote a function on my serializer
class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'

    def get_labels():
        return dict([(f.name, f.verbose_name) for f in MyModel._meta.fields + MyModel._meta.many_to_many])                                                                                                                                                                                          

I can then use

class MyModelRenderer(CSVRenderer):
    labels = MyModelSerializer.get_labels()

This a far from perfect, but it does the job for now 😎

fabienheureux avatar Sep 24 '19 13:09 fabienheureux