How to return id after saving a record django rest frwamework.
I'm trying to get the saved object right after saving.
Registration is successful, but the id is not returned.
empresa = EmpresaCreateSerializer(data=data)
empresa.user = user_id
if(empresa.is_valid()):
empresa.save()
print(empresa.id)
else:
return Response(empresa.errors)
AttributeError: 'EmpresaCreateSerializer' object has no attribute 'id'
Model
class Empresa(models.Model):
nome = models.CharField(max_length=255, null=True)
cnpj = models.CharField(max_length=15, null=True)
user = models.ForeignKey(User)
def __str__(self):
return self.nome
Serializer
class EmpresaCreateSerializer(serializers.ModelSerializer):
nome = serializers.CharField(allow_blank=True, allow_null=True)
cnpj = serializers.CharField(allow_blank=True, allow_null=True)
class Meta:
model = Empresa
fields = ('id','nome', 'cnpj', 'user')
You need to assign the value being returned from the save()
method:
obj = empresa.save()
print(obj.id)
The reason is that save()
calls create()
of the Serializer which returns an object instance
Hi you need do like this
empresa = EmpresaCreateSerializer(data=data)
empresa.user = user_id
if(empresa.is_valid()):
empresa.save() //Here you need use these two methods **create,perform_create**
print(empresa.data['id'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With