开发者

Django User ID fields

I am creating a new User object using the following code:

user = User(username=new_data['username'], email=new_data['email'], first_name=new_data['email'])
user.save()
user_id = user.id

Now, I开发者_运维百科 need to retrieve the id of the user into a variable called user_id. However, when I do this, user_id has the value of "Nothing". When I look in the database, however, I can see the newly created user entry in the database.

How can I get the id of the user record?


Try

user_id = user.pk

instead of

user_id = user.id


If you want to create a User, you could try the following:

user = User.objects.create_user(username=new_data['username'], email=new_data['email'])
print user.pk #Already works as create_user saves the new instance.
user.first_name = new_data['email'] #Can't assign to first_name in create_user.
user.save()
print user.pk #Will work.

By the way, this also normalizes the e-mail address & all.

If you need to assign other parameters, such as first name, just use your user variable, assign to these values and then save.

You should read up about Model managers if you want more information on this.


This isn't specific to django, but check out SQLAlchemy's handling of PostgreSQL's RETURNING:

http://www.sqlalchemy.org/docs/dialects/postgresql.html#insert-update-returning

I don't know how you'd coerce Django's ORM to make use of that, but SQLA's making use of pscopg2 to get RETURNING support.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜