0

I have a queryset that contains a field named 'foo' defined in a Bar model.

result = Bar.objects.values('foo').distinct()

I would like to return a queryset containing 'foo' and a slug version of 'foo'.

How can I do that without creating a new field in my Bar model?

Benjamin
  • 3,350
  • 4
  • 24
  • 49
  • Even if this is possible, you might need to add a new field to the model anyway. For example if you use the slug in the URL, then you need to add the field so that you can look up by slug. – Alasdair Dec 11 '17 at 15:04
  • But I will have to to that on 6 fields. It will take too much space on my disk (for nothing because I do a distinct on this fields as there are near that 10 different values) – Benjamin Dec 11 '17 at 15:07
  • Really? Do you seriously have such massively limited disk space? – Daniel Roseman Dec 11 '17 at 15:11
  • No but I will store 6 fields for nothing and it is obviously not the good way to do that. I am trying solve that with django rest framework at the serialization. – Benjamin Dec 11 '17 at 15:14

1 Answers1

1

A solution is using DRF: Django REST Framework: adding additional field to ModelSerializer

For me:

class BarSerializer(serializers.ModelSerializer):
    slug = serializers.SerializerMethodField('slug_field')

    @staticmethod
    def slug_field(bar):
        return slugify(bar['foo'])

    class Meta:
        model = Indicateur
        fields = ('foo', 'slug',)
Benjamin
  • 3,350
  • 4
  • 24
  • 49