2013-02-11 55 views
0

我有一個Event表,可存放2種類型的與會者:學生和工作人員。我將如何去檢索那些處於學生專欄(多對多)的人,並將他們放入他們自己的表中?從多對多列中檢索對象並放入新表

class Event(models.Model): 
    ... 
    students = models.ManyToManyField(StudentProfile, null=True, blank=True) 
    staff = models.ManyToManyField(StaffProfile, null=True, blank=True) 
    ... 

新表:??

class StudentAttendees(models.Model): 
    profile = models.ManyToManyField(StudentProfile, through='Event') 
    event = models.ForeignKey(Event) 
    created = models.DateTimeField(auto_now_add=True) 

回報:

django.core.management.base.CommandError: One or more models did not validate: 
profiles.studentattendees: 'profile' is a manually-defined m2m relation through model Event, which does not have foreign keys to StudentProfile and StudentAttendees 

感謝您的幫助提前。

回答

0

像這樣的東西可能會奏效:

for some_event in Event.objects.all(): 
    student_attendees_object = StudentAttendees.objects.create(event=some_event) 
    for student in some_event.students_set.all(): 
     student_attendees_objects.profile.add(student) 

我不知道你想實現什麼,但如果你需要對學生參加額外的信息,你可能要考慮中間表參數through。看看這個documentation

+0

我認爲,通過參數的中間模型是你所需要的。 – UnLiMiTeD 2013-02-11 18:36:32

+0

只是爲了澄清。我正在檢索學生與會者,主要僅將其顯示爲僅供後端使用。只是爲了更好地查看列表中的與會者。對不起,我沒有在我的文章中指定。 – Modelesq 2013-02-11 18:51:41

+0

@msc應該是一個model.Manager? – Modelesq 2013-02-11 19:14:31