从多个列检索对象并放入新选项卡

2024-04-26 05:12:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个活动表,可容纳两种类型的与会者:学生和教职员工。我该如何检索学生列中的人(多对多)并将他们放在自己的表中?你知道吗

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

提前谢谢你的帮助。你知道吗


Tags: eventtrue类型modelmodelsnotprofilenull
1条回答
网友
1楼 · 发布于 2024-04-26 05:12:07

像这样的方法可能有用:

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。你知道吗

相关问题 更多 >