[Answered ]-Django – AutoField with regards to a foreign key

2👍

You want that constraint at the database level. Otherwise you’re going to eventually run into the concurrency problem you discussed. The solution is to wrap the entire operation (read, increment, write) in a transaction.

Why can’t you use an AutoField for instead of a PositiveIntegerField?

number = models.AutoField()

However, in this case number is almost certainly going to equal yourmodel.id, so why not just use that?

Edit:

Oh, I see what you want. You want a numberfield that doesn’t increment unless there’s more than one instance of MyModel.business.

I would still recommend just using the id field if you can, since it’s certain to be unique. If you absolutely don’t want to do that (maybe you’re showing this number to users), then you will need to wrap your save method in a transaction.

You can read more about transactions in the docs:

http://docs.djangoproject.com/en/dev/topics/db/transactions/

If you’re just using this to count how many instances of MyModel have a FK to Business, you should do that as a query rather than trying to store a count.

Leave a comment