我想知道,更新多个字段的标准方法是什么,其中包括 django 中模型实例的相关字段? ...
Class User(models.Model):
id = models.CharField()
name = models.CharField()
dob = models.CharField()
Class Appointment(models.Model):
user = models.ForeignKey(User)
app_id = models.CharField()
time = models.DateTimeField()
status = models.CharField()
要更新约会模型中的多个字段,我可以这样做
dict ={
"app_id": "123",
"time": "2012-01-01 10:30",
"status": "Open"
}
Appointment.objects.filter(app_id=123).update(dict)
有没有办法更新相关模型?
如何更新约会模型和用户模型?
案例:
dict ={
"name": "foo",
"app_id": "123",
"time": "2012-01-01 10:30",
"status": "Open"
}
最佳答案
为了清楚起见 - 这不是“继承”的意思。约会与用户相关,但不继承自它。
查询集上的更新方法不能在一次调用中执行此操作。文档说:
the only restriction on the QuerySet that is updated is that it can only update columns in the model’s main table, not on related models.
https://docs.djangoproject.com/en/dev/ref/models/querysets/#update
如果你只有 app_id 而没有别的,你可以编写第二个更新调用:
User.objects.filter(appointment__app_id=123).update(name='foo')
关于django - 如何更新包含 django 模型实例的相关字段的多个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16570358/