[Answer]-Can I make Django return the ID for a record on create?

1๐Ÿ‘

# No reporters are in the system yet.
>>> Reporter.objects.all()
[]

# Create a new Reporter.
>>> r = Reporter(full_name='John Smith')

# Save the object into the database. You have to call save() explicitly.
>>> r.save()

# Now it has an ID.
>>> r.id
1

# Now the new reporter is in the database.
>>> Reporter.objects.all()
[<Reporter: John Smith>]

# Fields are represented as attributes on the Python object.
>>> r.full_name
'John Smith'

See also: https://docs.djangoproject.com/en/1.5/intro/overview/

๐Ÿ‘คMSJ

0๐Ÿ‘

The action of calling create saves the new instance to the database. result now has a pk attribute which is its id.

Note that result is the actual object, not the result of __str__. Plus, you can use the object, rather than its ID, to set as a foreignkey of another object.

๐Ÿ‘คDaniel Roseman

0๐Ÿ‘

result.pk should give you the primary key
โ€œpkโ€ is an alias to the field which is defined as the primary key.

๐Ÿ‘คCorinne Kubler

Leave a comment