The situation - I have a model and inline formset like:
class ProductImage(models.Model):
product = models.ForeignKey('Product')
display_order = models.PositiveSmallIntegerField(default=0)
class Meta:
unique_together = (('product', 'display_order'),)
inlineformset_factory(
Product, ProductImage, form=ProductImageForm, extra=1)
In the front end I provide a UI to reorder the images for a given product.
The problem:
<Product id=1>
.display_order=0
and display_order=1
respectively.display_order=0
while renumbering the existing images to display_order=2
and display_order=1
respectively.At this point I get a validation error for the unique check.
Looking through Django source code we find this in BaseModelFormSet.save
:
return self.save_existing_objects(commit) + self.save_new_objects(commit)
...ok that looks all good, it will save (update) the existing objects first. So from the perspective of the db there is no conflict in the unique constraints.
The problem is that saving comes after validation, or course, and at the point of validation the new objects will conflict with existing ones in the db.
It seems like BaseModelFormSet
needs some mechanism whereby it could take into account the about-to-be-updated values from its form instances.
Does anyone have a workaround that does not involve pushing the problem onto the user?