Arjun Baidya
Arjun Baidya

Reputation: 15

How to get foreignkey field value in django?

I have two model given below:

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)

here color field return colorName field's id but I need colorName field's value How to solve this?

Upvotes: 0

Views: 64

Answers (1)

iamdipta
iamdipta

Reputation: 366

serializers

# 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__'

create ColorSerializer if don't have,

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

:)

Upvotes: 1

Related Questions