Reputation: 161
I'm trying to create a new model2 whenever a new model1 is created and link these two models. Model2 have many to many relation with model1
@admin.register(model1)
class model1Admin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not obj.id:
obj.payments.add(model2.objects.create())
super().save_model(request, obj, form, change)
After trying the code above I get this error:
needs to have a value for field "id" before this many-to-many relationship can be used
I tried this:
def save_model(self, request, obj, form, change):
if not obj.id:
obj.save()
a = Payment.objects.create()
obj.payments.add(a)
super().save_model(request, obj, form, change)
I get no errors but still this won't make a relation between these two objects
Upvotes: 0
Views: 969
Reputation: 51
i think error message is clear here: your are trying to add a manyTomany relation (witch by the way is going to create an entry in a special table where links between model1 and model2 are going to be managed) to model1 , but model1 did not yet exist in the database so no record can't be create in the special manyTomany table so this error is raised.
To get ride of this you should first create the obj1 (by calling the save() method) , second create obj2 and then call the add() method to link the two together (this is the special entry in the manyTomany table is going to be create for your relation). Happy coding.
Upvotes: 1