如何在 Django 中获取外键字段值?
How to get foreignkey field value in 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)
这里是颜色字段 return 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__'
:)
下面给出了两个模型:
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)
这里是颜色字段 return 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__'