django - 如何在 django 信号 post_save 中使用 update_fields
问题描述
我希望我的标题足以理解我想说的话,如果不是那么请提前道歉。
我在插入数据时没有问题,但是当管理员更新学生已经记录的部分时怎么样?,我只想更新当前数据而不添加其他数据
这是我在 model.py(post_save) 中的代码。
@receiver(post_save, sender=StudentsEnrollmentRecord)
def create(sender, instance, created, **kwargs):
teachers = SubjectSectionTeacher.objects.filter(Courses=instance.Courses, Sections=instance.Section)
if created and teachers.exists():
StudentsEnrolledSubject.objects.create(
# This should be the instance not instance.Student_Users
Students_Enrollment_Records=instance,
# The below is also not an instance of SubjectSectionTeacher
Subject_Section_Teacher=teachers.first())
解决方案
您的代码还有其他问题(为什么要使用 CamelCase 作为属性?),但是在 Django 中,如果您想有条件地创建一个新对象,您可以使用update_or_create()
. 例子:
StudentsEnrolledSubject.objects.update_or_create(
pk=instance.pk, defaults={"enrollment_credits": enrollment_credits}
)
如果数据库中不存在,这将创建一个新StudentsEnrolledSubject
对象。instance.pk
否则,它将更新现有实例的enrollment_credits
.
推荐阅读
- c++ - 在 xCode 上安装 SDL2
- bluetooth - 使用 Core Bluetooth 与 Nissan Leaf 中的 LeLink OBD-II BLE 设备通信
- python - Python OpenCV - CascadeClassifier Haarcascade detectMultiScale()不起作用
- kubernetes - 使用模拟获取 GKE 集群凭据后无法运行“kubectl”命令
- parsing - 尽管数据处理在其他地方处理,但函数错误中的非详尽模式
- javascript - 样式化数据反应
- fortran - TINY(x) 内在函数
- jquery - 如何使用 jQuery 更改 HTML 页面?
- c# - 程序集定义无法解析来自外部包的命名空间
- d3.js - d3:当更多数据添加到条形图中时,无法获取要显示的值