简体   繁体   中英

Can I make Django return the ID for a record on create?

I'm using object.create to store a record to a django database:

     result = MyObject.objects.create(var1='foo',
                                      var2='bar',
                                         ...
                                     )

After this executes result is whatever string is returned by __str__ (I confirmed this by changing it to return self.id ). I'd like to have access to the primary key value, since the next step in some cases is to create another record which references this one via foreign key, but I'd really like __str__ to return something more meaningful than that.

I realize that I could grab the most recently created, but this will be threaded code with multiple concurrent users, so there's a potential for that to fail in truly unfortunate ways.

I'm using an SQLite db for development, but will switch to MySQL for production, so if there's a way to solve this that requires mySQL I can make the switch now.

Update - Never Mind

Okay, I figured out what was happening. On the first pass through the call to create doesn't happen, and while result was defined it wasn't an object.

Thanks, all. Digging further in response to your comments is what led me to find it.

< slinking off embarrassed >

# 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/

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.

result.pk应该给您主键“ pk”是定义为主键的字段的别名。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM