如何获取要显示的容器名称而不是 ID?

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

所以我想弄清楚如何在我考虑过使用 map 方法并从 ID 获取对象并从所述 ID 获取名称的视图中显示 ForeignKey 名称,但这似乎并没有工作。我可能做错了,但我不太确定。

JSON 回应

[
    {
        "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
    }
]

查看

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)

型号

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

序列化器


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


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

首先您可以使用ListCreateAPIView查看您的视图。

关于你的问题,请检查 this 并 将 DrinkSerializer 更新为

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

你可以这样做,我认为更好。

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