简体   繁体   English

如何在 django 信号 post_save 中使用 update_fields

[英]How to use update_fields in django signals post_save

I hope my title is enough to understant what i am trying to say if not then sorry in advance.我希望我的标题足以理解我想说的话,如果不是那么请提前道歉。

I dont have problem on inserting data, but how about when the admin update the section of student were the student have already record?, I just want to update the current data not add another data我在插入数据时没有问题,但是当管理员更新学生的部分时学生已经记录了怎么办?,我只想更新当前数据而不添加其他数据

this is my code in my model.py(post_save)..这是我在 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())

Your code has other problems (why are you using CamelCase for attributes?), but in Django if you want to conditionally create a new object, you can use update_or_create() .您的代码还有其他问题(为什么要使用 CamelCase 作为属性?),但是在 Django 中,如果您想有条件地创建一个新的 object,您可以使用update_or_create() Example:例子:

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

This will create a new StudentsEnrolledSubject object if instance.pk does not exist in the database.如果数据库中不存在instance.pk ,这将创建一个新的StudentsEnrolledSubject object。 Otherwise, it will update the existing instance's enrollment_credits .否则,它将更新现有实例的enrollment_credits

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

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