Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ID of a just created record in Django?

I'm using Django 1.3 for one of my projects and I need to get the ID of a record just saved in the database.

I have something like the code below to save a record in the database:

n = MyData.objects.create(record_title=title, record_content=content) n.save() 

The ID of the record just saved auto-increments. Is there a way to get that ID and use it somewhere else in my code?

like image 867
avatar Avatar asked Jun 06 '11 14:06

avatar


People also ask

How do I find my Django ID?

You can use exists() : if scorm. objects. filter(Header__id=qp.id).

Does Django auto generate ID?

Django will create or use an autoincrement column named id by default, which is the same as your legacy column.

Does Django create ID field?

By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field. If you add your own primary key field, the automatic one will not be added.

Is ID same as PK Django?

It doesn't matter. pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or object_id or whatever. It also provides more consistency if you have models with different primary key fields.


1 Answers

Use n.id after the save.

See "Auto-incrementing primary keys".

like image 128
JamesO Avatar answered Oct 07 '22 00:10

JamesO