Is it possible to get the all values of foreign key instead of id?

71 Views Asked by At

Is it possible to get all the values of foreign key instead of id?

class WishlistSerializer(serializers.ModelSerializer):

def to_representation(self, instance):
    rep = super(WishlistSerializer, self).to_representation(instance)
    rep['product'] = instance.product.name
    return rep
2

There are 2 best solutions below

0
On

Assuming you have a model structure like this:

class Product(models.Model):
    name = models.CharField(max_length=100)
class Wishlist(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    # more fields in your Wishlist model

Your Updated serializer :

class WishlistSerializer(serializers.ModelSerializer):
    product_name = serializers.CharField(source='product.name', read_only=True)

class Meta:
    model = Wishlist
    fields = ('product_name', 'other_field1', 'other_field2', ...)

def to_representation(self, instance):
    rep = super(WishlistSerializer, self).to_representation(instance)
    # You can remove the line below as the 'product_name' field will already be in the representation
    # rep['product'] = instance.product.name
    return rep

By creating a product_name field in your serializer and using the source parameter to specify the attribute path (product.name), you can retrieve the name attribute of the related product and include it in the representation of the Wishlist model. This way, you will get the product name instead of the product ID in the serialized output.

0
On

you can add serializer of Product model to WishlistSerializer.

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'


class WishlistSerializer(serializers.ModelSerializer):
    product = ProductSerializer(many=True, read_only=True)

    class Meta:
        model = Wishlist
        fields = ('id', 'name', 'product',)