django模型实例在保存后无法获取该字段

时间:2012-06-21 08:10:01

标签: django model

这是我的代码:

models.py

class TblUser(models.Model):
    uid = models.IntegerField(primary_key=True, db_column='ID') # Field name made lowercase.
    username = models.CharField(max_length=3072, db_column='UserName', blank=True) # Field name made lowercase.
    password = models.CharField(max_length=3072, db_column='PassWord', blank=True) # Field name made lowercase.
    datesstart = models.DateTimeField(null=True, db_column='datesStart', blank=True) # Field name made lowercase.
    datesend = models.DateTimeField(null=True, db_column='datesEnd', blank=True) # Field name made lowercase.
    num = models.IntegerField(null=True, db_column='Num', blank=True) # Field name made lowercase.
    power = models.IntegerField(null=True, db_column='Power', blank=True) # Field name made lowercase.
    email = models.CharField(max_length=12288, blank=True)
    class Meta:
        db_table = u'tbl_user'

    def __unicode__(self):
        return '%d--%s--%d'%(self.uid,self.username,self.power)

views.py

from app.models import TblUser
def appendUser(self,name,pwd):
    #I add a new user,and the primary_key:uid is autoincrement in datebase
    user = TblUser.objects.create(username=name,password=pwd)
    print user.uid#None

当我调用 appendUser()时,它会在datebase中插入一条新记录,而用户(TblUser的实例)只有两个有效字段(用户名,密码),另一个是空的。

我如何获得user.uid,因为我想通过使用它来处理其他事情?

2 个答案:

答案 0 :(得分:2)

您应该使用AutoField而不是IntegerField作为pk:https://docs.djangoproject.com/en/1.4/ref/models/fields/#autofield

答案 1 :(得分:0)

您可能希望阅读本文,使用ModelForm的不同方法:

Get Primary Key after Saving a ModelForm in Django