如何在django中获得外键字段值?



我有两个模型:

class Color(models.Model):
colorName = models.CharField(max_length=200, null=True, blank=True)
# _id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return str(self.colorName)

class Variant(models.Model):
product = models.ForeignKey(Product, on_delete= models.CASCADE, null=True,blank=True)
color = models.ForeignKey(Color, on_delete=models.CASCADE, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return str(self.product)

views.py

@api_view(['GET'])
def getProduct(request, pk):
product = Product.objects.get(_id=pk)
variants = Variant.objects.filter(product=product)
productserializer = ProductSerializer(product, many=False)
variantserializer = VariantSerializer(variants,many=True)
data = 
{'product_details':productserializer.data,'product_variants':variantserializer.data}
print(data)
return Response(data)

这里颜色字段返回colorName字段的id,但我需要colorName字段的值如何解决这个问题?

序列化器

# replace VariantSerializer with below code
class VariantSerializer(serializers.ModelSerializer):
product = ProductSerializer(many=True, read_only=True)
color = ColorSerializer(many=True, read_only=True)
class Meta:
model = Variant
fields = '__all__'

创建ColorSerializer,如果没有,

class ColorSerializer(serializers.ModelSerializer):
class Meta:
model = Color
fields = '__all__'

:

最新更新