Home > Net >  How do I get the name of the container to show instead of the id?
How do I get the name of the container to show instead of the id?

Time:04-25

So I am trying to figure out how to display the ForeignKey name in the view I have thought about using map method and get the object from the ID and getting the name from said ID, but that doesn't seem to work. I could be doing it wrong but I am not quite sure.

JSON Response

[
    {
        "id": 3,
        "name": "Coke",
        "description": "Cocaine Drink",
        "container": 3
    },
    {
        "id": 4,
        "name": "Another One",
        "description": "Dj Khaled Drink",
        "container": 3
    },
    {
        "id": 5,
        "name": "Testy",
        "description": "Westy",
        "container": 4
    }
]

View

class ListDrinks(APIView):

    authentication_classes = []
    permission_classes = []
    
    def get(self, request, format=None):
        drinks = Drink.objects.all()
        serializer = DrinkSerializer(map(DrinksId, drinks), many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = DrinkSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Models

class Container(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name


class Drink(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=500)
    container = models.ForeignKey(
        Container, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.name

Serializers


class DrinkSerializer(serializers.ModelSerializer):
    class Meta:
        model = Drink
        fields = ['id', 'name', 'description', 'container']


class ContainerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Container
        fields = ['id', 'name']

CodePudding user response:

First of all you can use ListCreateAPIView for your view check it later.

And for your question check this out and update the DrinkSerializer to this

class DrinkSerializer(serializers.ModelSerializer):
    container = serializers.CharField(source="container.name", read_only=True)
    class Meta:
        model = Drink
        fields = ['id', 'name', 'description', 'container']

And you can do this, I think is better.

    ...
    def get(self, request, format=None):
        serializer = DrinkSerializer(Drink.objects.all(), many=True)
        ...
  • Related