【问题标题】:how to associate value with specific form in formset in django如何将值与 django 表单集中的特定表单相关联
【发布时间】:2013-09-13 10:55:25
【问题描述】:

我想将相关的反对与表单集中的相应表单相关联。到目前为止,我有:

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

有谁知道我如何做到这一点?

【问题讨论】:

  • 你不能只使用 inline_formset,还是我遗漏了什么?
  • 如果关系是外键,这将起作用,但通知和部门使用通用外键。关系对象中的 object_id 未明确绑定到部门 id。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 2011-07-03
    • 2019-05-15
    相关资源
    最近更新 更多