Fix bug where order is wrong after adding objects
Fix bug where order is wrong after adding objects

This problem was caused by using the count of the objects in the intermediary join table as the starting sort value. This was insufficient because deleting objects would not update the sort values.

So imagine with a fresh database, you added 5 objects then deleted 3. The max sort value would be 4 (the 5th object would use the count prior to adding, hence 4), but when you add a new object, its sort value would be 2 (current count of intermediary objects), NOT 5!

This fixes that by querying for the maximum sort value in use by the source object's intermediary objects and using that as the starting sort value.

Since bulk_create() was introduced in Django 1.4 and there is a dummy atomic() implementation (that actually was not being used), there is no need to use a different implementation to create intermediary objects on Django 1.5. Also, this ensures the right database is being used for the transaction, which was not the case before.

gradel/django-sortedm2m,gradel/django-sortedm2m,gregmuellegger/django-sortedm2m,gradel/django-sortedm2m,gregmuellegger/django-sortedm2m,gregmuellegger/django-sortedm2m