如何将值与django中formset中的特定表单相关联

时间:2013-09-09 20:59:01

标签: django django-models django-queryset django-orm

我希望关联一个相关的对象反对formset中的相应表单。到目前为止,我有:

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

有谁知道我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

我决定不使用内联表单而是使用多个表单。