Django: Object of type Profile is not JSON serializable

I have a model called Order, Profile and Users. In my Order model, i want to access the Profile of the buyer and seller, so i wrote a function in the Order model to get the profile of the buyer and the seller.

class Orders(models.Model):
    service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name="service_orders")
    seller = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="seller")
    buyer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="buyer")

    def seller_profile(self):
        seller_profile = Profile.objects.get(user=self.seller)
        return seller_profile

    def buyer_profile(self):
        buyer_profile = Profile.objects.get(user=self.buyer)
        return buyer_profile

Now when i add the seller_profile and buyer_profile in my OrderSerializer in, and try accessing the api endpoint in the browser, it shows the error Object of type Profile is not JSON serializable, Do i need to serialize my Profile Model or something like that?

class OrderSerializer(serializers.ModelSerializer):

    class Meta:
        model = Orders
        fields = ['id','seller', 'buyer', 'buyer_profile', 'seller_profile', ...]
    def __init__(self, *args, **kwargs):
        super(OrderSerializer, self).__init__(*args, **kwargs)
        request = self.context.get('request')
        if request and request.method=='POST':
            self.Meta.depth = 0
            self.Meta.depth = 2

I dont have any ProfileSeriallizer, do i need it?



The DRF needs to know how to convert your Profile object into a native Python representation that can then be converted to JSON.

I have serialized my profile in but still getting the error

class ProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = [ 'pid', 'user', 'full_name', 'bio', 'country', 'image', 'address', 'phone', 'website', 'pin', 'facebook', 'instagram', 'twitter', 'whatsApp', 'verified', 'wallet', 'code', 'recommended_by',  'date']

Is there a place i need to use the Serialized Profile in My Order Model?

You need to use this Serializer on the view that it’s getting invoked.

But i already another serializer on the view

    serializer_class = OrderSerializer

Can i pass in multiple serializers?


I haved passed in the serilaizer along side the OrderSerializer like this

serializer_class = OrderSerializer, ProfileSerializer

Now i am getting this error

'tuple' object is not callable

I suggest that you review this section of the drf docs.
You need to tell to your OrderSerializer to use the ProfileSerializer for both of these keys: buyer_profile, seller_profile.
The very first example on the docs shows how to do this.

1 Like

That fixed it for me, thank you very much for your help.