Reputation: 665
I want to get id value passing in the serializer that is
id = serializers.IntegerField(label='ID')
in the function to get the profile object
def profile_info(self, obj)
But it giving the error id is
IntegerField
please pass the int or string
Can Anybody tell me how to get values passed in id field thanks. Down below is my serializer code
class UserSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(label='ID')
# print ('dadddaaa ',serializers.data)
profile = serializers.SerializerMethodField('profile_info')
username = serializers.CharField()
first_name = serializers.CharField()
last_name = serializers.CharField()
# Nazir = serializers.CharField()
# profile = UsersSerializer(Profile.objects.get(User.objects.get(pk=serializers.data['id'])))
def profile_info(self, obj):
# print ('selffff ', serializers)
prof_obj = Profile.objects.get(user=User.objects.get(pk=id))
return {'id':prof_obj.id}
Upvotes: 2
Views: 22201
Reputation: 209
In Django Rest Framework every serializer extends from the upper class Field so to obtain a value, you most call to_internal_value or to_representation. This process runs automatically on your serializer over each field when you call .is_valid. In your case because you need the value of one Field the best option is skip this process and access using:
self.initial_data.get("your field name")
This return the original value passed to the serializer without validate. If you know that the function profile_info will be called after run a serializer.is_valid i recommend to access the value using:
self.validated_data.get("your field name")
Always use .get to get a value in a dictionary because by default returns None in the case that key does not exist. Using brackets will be raise an exception in the same escenario.
Upvotes: 2
Reputation: 995
The main issue here is that you are passing an IntegerField
object as an id in this query:
Profile.objects.get(user=User.objects.get(pk=id))
Try this instead:
Profile.objects.get(user=User.objects.get(pk=obj.id))
Full example:
class UserSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(label='ID')
# print ('dadddaaa ',serializers.data)
profile = serializers.SerializerMethodField('profile_info')
username = serializers.CharField()
first_name = serializers.CharField()
last_name = serializers.CharField()
# Nazir = serializers.CharField()
# profile = UsersSerializer(Profile.objects.get(User.objects.get(pk=serializers.data['id'])))
def profile_info(self, obj):
# print ('selffff ', serializers)
prof_obj = Profile.objects.get(user=User.objects.get(pk=obj.id))
return {'id':prof_obj.id}
Upvotes: 0
Reputation: 1571
I was searching for an answer but none of the worked for me but i got it from django it self
you can get it by using initial_data as inital_data returns the query dictionary
self.initial_data['id']
Upvotes: 4
Reputation: 3038
I would not recommend retrieving the related Profile model with a SerializerMethod, because this will fire a separate query for each User. I suggest to use a nested Serializer for the Profile model, so Django/DRF will build a JOIN query. Also, you don't have to specify each field, you can use the fields
option of the Meta
class.
First, make sure that you specify a related_name
for the user-relation in your Profile
model, so it will be accessible as a field in the ModelSerializer:
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='profile',
)
Then create a Serializer for each model:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('id', 'ship', 'copilot')
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer(read_only=True)
class Meta:
model = User
fields = ('id', 'profile', 'username', 'first_name', 'last_name')
This will give you a JSON like this:
{
"id": 1,
"profile": {
"id": 1,
"ship": "Millennium Falcon",
"copilot": "Chewbacca"
},
"username": "hsolo",
"first_name": "Han",
"last_name": "Solo"
}
Note: By default nested relations are not writable, but it can be done by creating your own create() and update() functions
Upvotes: 0