Django外键不会改变

时间:2015-05-06 21:29:39

标签: python django

我在Django中有一个有趣的(!)问题。 我想更改外键。我的代码:

print(todos[ind].list)
print(newList)
todos[ind].list = newList
print(todos[ind].list)
todos[ind].save()
print(todos[ind].list)

它的输出:

oldList
newList
oldList
oldList

我的模特:

class Todo(models.Model):
    name = models.CharField(max_length=255)
    list = models.ForeignKey(TodoList)

    def __str__(self):
        return str(self.name)

和todos list def:

todos = Todo.objects.filter(list = ls)

其中,ls和newList是:

ls = TodoList.objects.get(pk = list_id)
newList = TodoList.objects.get(pk = 1)

提前致谢。

1 个答案:

答案 0 :(得分:0)

todos是类似列表的查询集,但不是真正的列表。每次访问todos[ind]时,都会遇到db并加载新的模型实例。

所以将代码更改为:

todo = todos[ind]

print(todo.list)
print(newList)
todo.list = newList
print(todo.list)
todo.save()
print(todo.list)

或者您可以将查询集缓存到列表中,然后像您在问题中那样通过索引访问实例:

todos = list(Todo.objects.filter(list=ls))

print(todos[ind].list)
todos[ind].list = newList
print(todos[ind].list)