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 serializer.py
, 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
else:
self.Meta.depth = 2
I dont have any ProfileSeriallizer, do i need it?