简体   繁体   English

将父级和子级模型对象保存在一起

[英]Save parent and child model object together

I use Django 2.0 and mysql database and my project model is like: 我使用Django 2.0和mysql数据库,我的项目模型如下:

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. 在Flask(使用postgresql)中有add(object)和add_all([parent,child])方法,我使用了add_all,所以如果child有错误,parent就不会保存。

but in Django I couldn't find this method. 但在Django我找不到这种方法。

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 PS:我读了这个链接,我认为“SET”方法是我需要的,但我不知道如何使用它,如果它是解决方案: django关系

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 : 下面是使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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