Django 1.8:使用cleaning_data的问题

时间:2017-01-16 14:20:44

标签: django python-2.7 django-forms

我有一个奇怪的问题。我正在使用与从Model返回的数据绑定的Select字段。它被定义为:

choices = Subscription.objects.filter(is_full_version=False)
subscription_id = forms.ModelChoiceField(queryset=choices)

request.POST会从id选项的value属性返回form.cleaned_data.get('subscription_id')但是当我打电话时: 'subscription_id': <Subscription: Gold>它会返回:

Gold

request.POST是文字而非Id。

subscription_id': [u'3']宁愿返回我想要的东西: public class APInvoiceEntryExt:PXGraphExtension<APInvoiceEntry> { public PXAction<APInvoice> LaunchOpenSource; [PXButton(CommitChanges = true)] [PXUIField(DisplayName = "Open Source")] protected void launchOpenSource() { APInvoice apinvoice = (APInvoice)Base.Document.Current; if (apinvoice != null) { AssistantController.OpenSourceDataMaint graph = PXGraph.CreateInstance<AssistantController.OpenSourceDataMaint>(); graph.OpenSourceDataHeader.Current = graph.OpenSourceDataHeader.Search<AssistantController.xTACOpenSourceHeader.openSourceName ,AssistantController.xTACOpenSourceHeader.dataID>("Bills and Adjustments", apinvoice.RefNbr); throw new PXRedirectRequiredException(graph, "Open Source") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } } }

那是什么?

1 个答案:

答案 0 :(得分:2)

当您从ModelChoiceField获取cleaned_data的值时,您将获得模型实例,而不是ID。

从实例中获取主键很容易。请记住处理None

subscription = form.cleaned_data.get('subscription_id')
if subscription is not None:
    subscription_id = subscription.pk