I use Django 2.0 and mysql database and my project model is like:
name = models.CharField()
number = models.IntegerField()
parent = models.ForeignKey(Parent)
what I want is to save both parent and child object together at the same time so that if in any case the child object has error(like number field is “some text”) and can not be saved the parent object doesn’t save.
in Flask (with postgresql) there is add(object) and add_all([parent, child]) methods and I used add_all so if child has error parent doesn’t save neither.
What I want is to save both parent and child object together at the same time so that if in any case the child object has error […] and can not be saved the parent object doesn’t save.
Sounds to me like you can use a database transaction for this. Within a transaction, either all the operations go through, or all of them get rolled back, no half-ways (no child is saved without the parent being saved in your case)
from django.db import DatabaseError, transaction
parent = Parent(name = "my name")
child = Child(number=3, parent=parent)
# Handle the case where an error prevented the operation