0

我有一个活动表,可容纳 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

提前感谢您的帮助。

4

1 回答 1

0

Something like this might work:

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)

I don't know what you're trying to accomplish, but if you need extra info on the student attendees, you might wanna look into an intermediate table with the through parameter. Check out the documentation on this.

于 2013-02-11T18:12:46.557 回答