Django ORM使用所有相关字段保存对象

时间:2018-05-23 13:02:36

标签: django django-models django-orm

在我的开发中,当我需要使用所有选定的相关对象保存模型对象时,我遇到了这种情况。听起来很奇怪但是当你不知道模型对象做了哪些操作时它很有用。 例如:

class User(models.Model):
    name = models.CharField(max_length=50)

class Room(models.Model):
    user = models.OneToOneField(User)
    size_x = models.SmallIntegerField()
    size_y = models.SmallIntegerField()

def do_some_stuff(room):
    room.user.name = "some new name"         

room = Room.objects.get(id="some_id")
do_some_stuff(room) # we didn't know which related_fields would be loaded and modified here
room.save() # <- here I want to save the room object and the user (if the user object was fetched or modified from db)

也许有一些方法可以递归地获取所有已加载的相关对象?

感谢。

0 个答案:

没有答案