1

I have multiple Product objects in my project. I want to create a form which updates all Product objects at once. Since Product has many attributes I want to spare some time and do it using ModelForm but I can't figure out how to do that.

So there is no particular object I want to update, instead there is many of these objects but I want to set the same attributes for all but not change id (and one other field - OneToOne).

I think this might be a solution but can't finish save method.

class UpdateMultipleProductObjects(forms.ModelForm):

    class Meta:
        model = Product
        fields = '__all__'
        exclude = ['id',...]

    def save(self, *args, **kwargs):
        temporary_object = super(UpdateMultipleProductObjects,self).save(commit=False,*args,*kwargs)
        update_dict = {x.name : getattr(temporary_object,x.name) for x in temporary_object ._meta.fields if x.name not in ['id',...]}
        Product.objects.all().update(**update_dict)

Do you have any ideas or better/safer solution?

Milano
  • 18,048
  • 37
  • 153
  • 353
  • This question is not clear. Do you want a form for each Product, or do you want to set all Products to the same values? And what is the point of your `temporary_object`? – Daniel Roseman May 29 '17 at 10:23
  • @DanielRoseman I want to set all Products to the same values (but they might be different before). Temporary object is like a template for products updating. It contains all necessary information so I didn't have to write all attributes explicitly. – Milano May 29 '17 at 10:25
  • @DanielRoseman I've edited the code. Do you think that there is a better solution? – Milano May 29 '17 at 10:29

1 Answers1

2

The temporary object seems pointless. It would be easier to update from the form's cleaned data directly:

Product.objects.update(**self.cleaned_data)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895