简体   繁体   English

Django外键不变

[英]Django Foreign Key does not change

I have a funny(!) problem in Django. 我在Django中有一个有趣的问题! I want to change a Foreign key. 我想更改外键。 my code: 我的代码:

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

it's output: 它的输出:

oldList
newList
oldList
oldList

My Model: 我的模特:

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

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

and todos list def: 和待办事项清单def:

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

Where, ls and newList is: 其中,ls和newList是:

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

Thanks in advance. 提前致谢。

todos is a list-like queryset but not a real list. todos是一个类似于列表的查询集,但不是真实列表。 Every time you access todos[ind] you get the hit into db and load new model instance. 每次访问todos[ind]您都将命中数据库并加载新的模型实例。

So change you code to: 因此,将您的代码更改为:

todo = todos[ind]

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

Or you can cache the queryset into list and then access to the instances by index like you did in your question: 或者,您可以将查询集缓存到列表中,然后像在问题中一样通过索引访问实例:

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

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

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

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