Django [SOLVED]: Save parent and child model object together

Django [SOLVED]: Save parent and child model object together

Home Forums Frameworks Django Tutorials Django [SOLVED]: Save parent and child model object together

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #246514

    Cloudy Point
    Keymaster

    QuestionQuestion

    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

    #246515

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    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
    

    Source: https://stackoverflow.com/questions/47965482/save-parent-and-child-model-object-together
    Author: bakkal
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.