首页 > 解决方案 > 如何在 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())

标签: django

解决方案


您的代码还有其他问题(为什么要使用 CamelCase 作为属性?),但是在 Django 中,如果您想有条件地创建一个新对象,您可以使用update_or_create(). 例子:

StudentsEnrolledSubject.objects.update_or_create(
        pk=instance.pk, defaults={"enrollment_credits": enrollment_credits}
)

如果数据库中不存在,这将创建一个新StudentsEnrolledSubject对象。instance.pk否则,它将更新现有实例的enrollment_credits.


推荐阅读