ralfe
ralfe

Reputation: 1454

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?

Upvotes: 6

Views: 12323

Answers (3)

Thomas Orozco
Thomas Orozco

Reputation: 55207

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.

Upvotes: 3

Sean
Sean

Reputation: 10206

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.

Upvotes: 0

pvoosten
pvoosten

Reputation: 3287

Try

user_id = user.pk

instead of

user_id = user.id

Upvotes: 5

Related Questions