Django user id fields

I create 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 get the user id in the user_id variable. However, when I do this, user_id is set to "Nothing". However, when I look in the database, I see a newly created user record in the database.

How can I get a user record id?

+4
source share
3 answers

If you want to create a user, you can 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 email address and that’s it.

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

You should read about model managers if you want more information about this.

+1
source

Try

user_id = user.pk

instead

user_id = user.id

+3
source

This does not apply to django, but check SQLAlchemy PostgreSQL RETURNING processing:

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

I don't know how you could use Django ORM, but SQLA uses pscopg2 to support RETURNING .

0
source

All Articles