我想将相关的反对与表单集中的相应表单相关联。到目前为止,我有:
ModelFormSet = modelformset_factory(Notification, form=NotificationsForm, extra=5)
generic_type = ContentType.objects.get_for_model(Department)
queryset = Notification.objects.filter(notificationrelation__content_type_id=generic_type.id)
formset = ModelFormSet(queryset=queryset)
for notification in formset.get_queryset():
relation = NotificationRelation.objects.get(notification=notification)
department = Department.objects.get(pk=relation.object_id)
我的模型如下所示:
class Notification(models.Model):
name = models.CharField('Notification Name', max_length=128)
class Department(models.Model):
name = models.CharField('Department Name', max_length=128)
class NotificationRelation(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(null=True, blank=True)
content_object = generic.GenericForeignKey('content_type', 'object_id')
notification = models.ForeignKey(Notification)
我想将最后一行的部门与表单集中的相关通知联系起来。
就像是:
for form in formset:
if something:
form.department = department
有谁知道我怎么能做到这一点?