如何在保存记录后返回id django rest frwamework

时间:2017-09-07 04:10:19

标签: django django-rest-framework

如何在保存记录django rest frwamework后返回id。

我试图在保存后立即获取保存的对象。

注册成功,但不返回ID。

    empresa = EmpresaCreateSerializer(data=data)
    empresa.user = user_id
    if(empresa.is_valid()):
        empresa.save()
        print(empresa.id)
    else:
        return Response(empresa.errors)
  

AttributeError:' EmpresaCreateSerializer'对象没有属性   ' ID'

模型

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

串行

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')

2 个答案:

答案 0 :(得分:4)

您需要指定从save()方法返回的值:

obj = empresa.save()
print(obj.id) 

原因是save()调用Serializer的create()返回一个对象实例

答案 1 :(得分:0)

嗨,你需要这样做

function getReturn() {
  var risk = document.forms[0];
  var slideAmount = document.getElementById("slideAmount").value;
  var txt;
  var returns;
  for (var i = 0; i < risk.length; i++) {
    if (risk[i].checked) {
      txt = risk[i].value;
    } //for
    if (txt == 1) {
     returns = slideAmount * 0.06;
    } else if (txt == 2) {
     returns = slideAmount * 0.11;
    } else if (txt == 3) {
     returns = slideAmount * 0.17;
    }
  } //for
  document.getElementById("returns").innerHTML = "ESTIMATED RETURN PA: <span style='color:red'><i class='fa fa-usd fa-lg'></i>" + Math.ceil(returns) + "</span>";
}