Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return id after saving a record django rest frwamework

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')
like image 594
marcelo.delta Avatar asked Sep 07 '17 04:09

marcelo.delta


2 Answers

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

like image 188
Jahongir Rahmonov Avatar answered Sep 21 '22 15:09

Jahongir Rahmonov


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'])
like image 38
Robert Avatar answered Sep 17 '22 15:09

Robert