Monday, October 31, 2016

BaseInlineFormSet with unique_together Model

Good day,

I am new to this list, but I would like to understand better what is going on and how I can fix it the Django way.

 

I have a model similar to the ingredients list of a recipe.

class FoodItem(models.Model):

                name = models.CharField()

 

class Recipe(models.Model):

                input = models.ForeignKey(FoodItem, related_name=”recipe”, …)

                qty = models.FloatField()

                ingredient = models.ForeignKey(FoodItem, …)

 

                class Meta:

                                unique_together = (‘input’, ‘ingredient’)

 

We don’t want the recipe to list the same ingredient twice.

Then I make a basic BaseInlineFormSet.  I use Javascript to add forms and delete forms dynamically.  So let’s say I first create this data:

Input, Qty, Ingredient

Cookies, 1, Sugar

Cookies, 2, Eggs

Cookies, 4, Flour

Cookies, 1, Chocolate Chips

 

It’s perfect.  Then I go back and try to update the data.  I remove the Flour from the recipe.  It gets marked for deletion and hidden from the user.  Then I think, “Oh wait!  That was supposed to be 6 of the Flour!”  So I add a new data entry form to the formset with this data:

Cookies, 6, Flour

 

I click on save, and I get a validation error.  That input and ingredient already exist.  And it’s right.  The form marked for deletion that has 4 Flour does not get deleted until the call to formset.save().  But the new form is not valid because it violates the unique constraint on the model.  I did develop a roundabout way of dealing with the situation: I simply delete all the instances from the database for forms that are marked for deletion before calling formset.is_valid().  But I keep thinking to myself that there must be something I am missing.

 

Thank you,

Matthew Pava

 

 

 

No comments:

Post a Comment