I have a very simple Model:
class SomeParentModel(models.Model):
description = models.TextField(max_length=512, blank=True)
created = models.DateTimeField(auto_now_add=True)
class SomeModel(SomeParentModel):
number = models.BigIntegerField() # not unique!
created_date = models.DateTimeField(auto_now_add=True)
somefield = models.ForeignKey(...)
someotherfield = models.BooleanField(blank=True)
and I want to save multiple instances of Nbr
objects at once:
class SomeModelSetForm(forms.ModelForm):
last_number = Nbr.objects.order_by("-number").first().number
start_number = forms.IntegerField(required=True, initial=last_number+1)
end_number = forms.IntegerField(required=True, initial=last_number+1)
class Meta:
model = SomeModel
fields = ["start_number", "end_number", ...]
exclude = ["number"]
def clean(self):
cleaned_data = super().clean()
s = int(cleaned_data["start_number"])
e = int(cleaned_data["end_number"]) + 1
self.numbers = [n for n in range(s, e)]
def save(self, commit=False)
instances = []
for nbr in self.numbers:
instances.append(SomeModel(number=nbr, ....))
SomeModel.objects.bulk_create(instances)
return instances ## tried: return instances[0]
This leads to an AttributeError: 'list' object has no attribute 'save'
So I thought I could maybe just return the last object from instances
which throws the error: AttributeError: 'SomeModelSetForm' object has no attribute 'save_m2m'. Did you mean: '_save_m2m'?
How can i create one object per number in my numbers
list correctly or how can I call a new save
method for every element in my list?