I am trying to fetch related data from a parent table using an API. I am trying to get the details from the operator table which has a one-to-one field with the user table. After going through various answers I understood how to join tables but due to some reason I am unable to fetch the user data
class OpDetailsSerializer(DynamicFieldsModelSerializer):
user = UserSerializer(source="operator_details",many=False, read_only=True)
print(user.data)
class Meta:
model = OperatorDetails
fields = ('gst_no','pan','user')
class OperatorDetails(models.Model):
operator=models.OneToOneField(settings.AUTH_USER_MODEL,related_name="operator_details",on_delete=models.CASCADE,primary_key=True)
pan = models.CharField(max_length=10, unique=True, null=True,blank=True)
gst_no = models.CharField(max_length=15, unique=True,null=True,blank=True)
def __str__(self):
return str(self.operator)
def view_operator_info(request):
fields = ('operator','pan','gst_no','user')
operator = OperatorDetails.objects.get(operator__id=request.user.id)
serializer = OpDetailsSerializer(operator,fields=fields)
content = {
"status": True,
"response": status.HTTP_200_OK,
"message": "Operator details",
"data":serializer.data
}
return Response(content)
Actual Output
{
"status": true,
"response": 200,
"message": "Operator details",
"data": {
"gst_no": "test",
"pan": "test"
}
}
expected Output
{
"status": true,
"response": 200,
"message": "Operator details",
"data": {
"gst_no": "test",
"pan": "test",
"user":{
"email":.....
//data from user table
}
}
}
can anyone help. Thanks in advance
Your field name has to match the field on our model the other option is to use the source
parameter.
class OpDetailsSerializer(DynamicFieldsModelSerializer):
user = UserSerializer(source="operator", many=False, read_only=True)
print(user.data)
class Meta:
model = OperatorDetails
fields = ('gst_no','pan','operator')
class OperatorDetails(models.Model):
operator = models.OneToOneField(settings.AUTH_USER_MODEL,related_name="operator_details",on_delete=models.CASCADE,primary_key=True)
pan = models.CharField(max_length=10, unique=True, null=True,blank=True)
gst_no = models.CharField(max_length=15, unique=True,null=True,blank=True)
def __str__(self):
return str(self.operator)
def user(Self):
return {
'email':self.operator.email,
'firstname':self.first_name,
'lastname':self.last_name
}
Add the method user in your model OperatorDetails and try it. These thing helps me lot for making custom objects in my projects and share your review after you try these so i can can also take note.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.