【发布时间】:2019-09-02 12:28:36
【问题描述】:
我的 Django 模型中有以下模型
class Match(models.Model):
initiator = models.ForeignKey('CustomUser', related_name='match_initiator', on_delete=models.CASCADE)
matched_person = models.ForeignKey('CustomUser', related_name='matched_person', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
algo_version = models.IntegerField()
room_no = models.ForeignKey('Room', related_name='room_match', on_delete=models.CASCADE, null=True, blank=True)
class Room(models.Model):
name = models.CharField(max_length=20, unique=True)
members = models.ManyToManyField(CustomUser, related_name="joined_rooms")
created_at = models.DateTimeField(auto_now=True,editable=False)
is_active = models.BooleanField(default=True)
所以基本上我有两个模型,Room 和 Match,其中 Match 有一个房间的外键。现在我想一次创建这两个对象,但我不能这样做,因为首先我必须创建 Room 对象获取它的 id 并将其分配给 Match 对象实例,然后再次保存它。这样做的问题是,如果任何模型保存失败,它就会破坏代码。
有什么方法可以同时创建 Match 和 Room 对象吗?
我在 Django 文档中找到了这个 reference:但我不确定 Django 是自动处理它还是我需要处理它。
提前致谢!!!
【问题讨论】:
标签: django django-models django-rest-framework django-serializer