Search code examples
pythondjangojsondjango-rest-frameworkjsonserializer

JSON from django rest Framework


I'm making a API with django rest framework, but the JSON has the the categoria's id of categoria model, the foreignkey, I want show the categoria's name equals the model's id

class Establecimiento(models.Model):
    nombre= models.CharField(max_length = 140)
    categoria = models.ForeignKey(Categoria)
    ciudad = models.ForeignKey(Ciudad)
    def __unicode__(self):
        return self.nombre


class Categoria(models.Model):
    titulo = models.CharField(max_length = 140)

I have a file serializers.py a views.py whit ViewSet

class EstablecimientoSerializer(serializers.ModelSerializer):
#    establecimiento = Establecimineto.objects.values('categoira__titulo')
    class Meta:
        model = Establecimiento.objects.select_related('categoria')
#      model = Establecimiento
        fields = ('nombre','categoria',)
#
class EstablecimientoViewSet(viewsets.ModelViewSet):
#    queryset = Establecimiento.objects.all()
    queryset = Establecimiento.objects.values('nombre','categoria__titulo')
    serializer_class = EstablecimientoSerializer

Then when I make the query in the views.py the JSON result only show the fields null where I should make the query for that the JSON resulting not show id the Foreignkey


Solution

  • This is how your serializer should be defined:

    class EstablecimientoSerializer(serializers.ModelSerializer):
        categoria = serializers.RelatedField()
    
        class Meta:
            model = Establecimiento
            depth = 1
            fields = ('nombre', 'categoria',)
    

    and the viewset:

    class EstablecimientoViewSet(viewsets.ModelViewSet):
        queryset = Establecimiento.objects.only('nombre','categoria',)
        serializer_class = EstablecimientoSerializer
    

    This assumes that you have defined __unicode__ method for Categoria:

    class Categoria(models.Model):
        # fields..
    
        def __unicode__(self):
            return self.titulo
    

    If you don't want to define __unicode__, you can instead of RelatedField use the SlugRelatedField field:

    categoria = serializers.SlugRelatedField(read_only=True, slug_field='titulo')