从多对多列中检索对象并放入新表中

时间:2013-02-11 17:54:52

标签: python django django-models many-to-many

我有一个活动表,可容纳两种类型的与会者:学生和员工。我将如何检索那些在学生专栏(多对多)并将其放入自己的桌子中的人?

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

提前感谢您的帮助。

1 个答案:

答案 0 :(得分: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