Question

I need to store matches in my database and those matches already have a unique ID where they come from. For further assistance and referring, it is best for me to keep this ID:

match = Match(id=my8digitsid)
match.save()

However, incoming matches (not played yet) don't have an ID yet. Can I safely save my match as follow:

match = Match()
match.save

And then, once the match played modify it as such:

match.id = my8digitsid

When I say safely, I mean whether or not that the default ID generated (auto-incremented I guess) is unique and won't have any conflicts with my self-made IDs.

Was it helpful?

Solution

Yes, you can be sure that the ORM will make unique id's as referred in the documentation here. The database is the one calculating the new number.

If a model has an AutoField — an auto-incrementing primary key — then that auto-incremented value will be calculated and saved as an attribute on your object the first time you call save():

>>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b2.id     # Returns None, because b doesn't have an ID yet.
>>> b2.save()
>>> b2.id     # Returns the ID of your new object. There’s no way to tell what the value of an ID will be before you call save(), because

that value is calculated by your database, not by Django.

For convenience, each model has an AutoField named id by default unless you explicitly specify primary_key=True on a field in your model.

You can also provide the Id if you want using this. I copy below the info from Django documentation.

Explicitly specifying auto-primary-key values If a model has an AutoField but you want to define a new object’s ID explicitly when saving, just define it explicitly before saving, rather than relying on the auto-assignment of the ID:

>>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
>>> b3.id     # Returns 3.
>>> b3.save()
>>> b3.id     # Returns 3.

If you assign auto-primary-key values manually, make sure not to use an already-existing primary-key value! If you create a new object with an explicit primary-key value that already exists in the database, Django will assume you’re changing the existing record rather than creating a new one.

Given the above 'Cheddar Talk' blog example, this example would override the previous record in the database:

b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')
b4.save()  # Overrides the previous blog with ID=3!

But I don't recommend You to assign that ID yourself. I think more convenient to create a field of the model with the ID from where they come from.

The reason Why I don't recommend this is because you will have to verify always that the id provided has not been used before before inserting it. As a general rule I try to avoid modifying the standard behaviour of Django as much as possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top