简体   繁体   中英

Save parent and child model object together

I use Django 2.0 and mysql database and my project model is like:

class Parent(models.Model):
    name = models.CharField()

class Child(models.Model):
    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.

but in Django I couldn't find this method.

the default method is:

parent = Parent(name = "my name")
parent.save()

child = Child(number=3, parent=parent)
child.save()

what I want is something like this:

parent = Parent(name = "my name")
child = Child(number=3, parent=parent)

and then:

child.save(with related parent)

or:

save(parent, child together)

PS: I read this link and I think "SET" method is what I need but I'm not sure how to use it and if it's the solution: django relations

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)

Below is an example using transaction.atomic :

from django.db import DatabaseError, transaction
try:
    with transaction.atomic():
        parent = Parent(name = "my name")
        parent.save()

        child = Child(number=3, parent=parent)
        child.save()

except DatabaseError:
    # Handle the case where an error prevented the operation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM