1

When I create a PotatoBatch item via my admin form, I want many Potato objects to be created.

Potato has a ForeignKey to PotatoBatch.

I made a PotatoBatchCreateForm that has an extra field, "number_of_potatoes". When I save this form, I want it to generate the correct number of potatoes for this batch.

I wanted to override my PotatoBatchCreateForm's save method like this :

    def save(self, commit=True):
        potato_batch = super().save() # save the potato_batch object in order to have an object id
        number_of_potatoes = self.cleaned_data['number_of_potatoes']
        for i in range(number_of_potatoes):
            potato_batch.potato_set.create()
        return potato_batch

But this fails with a 'PotatoBatchCreateForm' object has no attribute 'save_m2m' error.

How can I resolve this ?

1 Answers1

0

You cannot create the m2m relationships until after the instance is saved. From your brief example I think this would work.

for i in range(number_of_potatoes):
    myPotato = Potato.objects.create()
    myPotato.potato_batch = potato_batch
    myPotato.save()
return potato_batch

More In-depth explanation: How to create an object for a Django model with a many to many field?

Erik
  • 412
  • 1
  • 5
  • 11
  • Hi @Erik. It's not an m2m relationship though, it's a foreignkey/one-to-many, so why is it affected ? – MonsieurPoivron Aug 30 '20 at 11:00
  • @MonsieurPoivron That is a good point, I don't know. Its difficult to tell with the limited context, but it could be a factor of using objects.create(). Most examples I see and use have an instance being created with the constructor i.e. myPotato = Potato(), saving it, and then relationships are created through signals. I usually use bulk_create() in this situation. Just create Potato() instances inside of your loop, include the potato_batch reference as you have been and append each instance to a list. Then when your loop is finished just do Potato.objects.bulk_create(list_of_potatoes) – Erik Aug 30 '20 at 18:24