在我的开发中,当我需要使用所有选定的相关对象保存模型对象时,我遇到了这种情况。听起来很奇怪但是当你不知道模型对象做了哪些操作时它很有用。 例如:
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)
也许有一些方法可以递归地获取所有已加载的相关对象?
感谢。