django admin - select reverse foreign key relationships (not create, I want to add available)

前端 未结 4 1484
南旧
南旧 2021-02-14 02:09

Lets say I have a model School and another model Student.

class Student(models.Model):
   school = models.ForeignKey(School)
   name =          


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-14 02:41

    I did what felix suggested. the only problem is that it gives a error like this:

    ValueError: Unsaved model instance  cannot be used in an ORM query.
    

    and the reason I found was that you can not change the foreign key in student's object BEFORE saving your current School model. because there is nothing to add to fk attribute yet! so use felix solution but in save_model function use the obj.save() before "for"

       def save_model(self, request, obj, form, change):
           original_students = obj.student_set.all()
           new_students = form.cleaned_data['students']
           remove_qs = original_students.exclude(id__in=new_students.values('id'))
           add_qs = new_students.exclude(id__in=original_students.values('id'))
    
    
           obj.save()   
    
           for item in remove_qs:
                   obj.student_set.remove(item)
           for item in add_qs:
                   obj.student_set.add(item)
               
    

提交回复
热议问题