2

我在使用不“指向”其相关表的主键的外键时保存 ModelForm 时遇到问题(遗留模式问题)我使用 to_field= 作为我的外键,以便它与一个键相关这不完全是一个关键。我的 ModelForm 外键使用带有查询集的 ModelChoiceField 和 HiddenInput() 小部件,因为默认渲染需要 2 分钟。当我尝试保存时,我得到一个无效的选择,因为查询集在返回相关对象(签入)时返回主键作为选项值。我怎样才能在此设置中使用 ModelChoiceField?我的基本架构如下。

class Checkin(models.Model):
    sampleid = models.CharField(unique=True, max_length=255, db_column='SampleID', primary_key=True)
    #shortsampleid is the field that is sometimes used as a sort of pk. 
    shortsampleid = models.IntegerField(unique=True, db_column='ShortSampleID') 
    company = models.CharField(max_length=765, db_column='Company', blank=True)
    ...

class Tblshipmentstore(models.Model):
    shortsampleid = models.ForeignKey(Checkin, to_field='shortsampleid', db_column='ShortSampleID')
    shipmentitem = models.CharField(max_length=765, db_column='ShipmentItem', blank=True)
    shipdate = models.DateField(null=True, db_column='ShipDate', blank=True)
    ...

class TblShipmentstoreForm(ModelForm):
    shortsampleid = forms.ModelChoiceField(queryset=Checkin.objects.all(), widget=forms.HiddenInput());

   class Meta:
       model = 'Tblshipmentstore'
4

1 回答 1

4

ModelChoiceField 有一个未记录的to_field_name参数,您可以在构造时传入该参数,这使得它使用该字段而不是主键。

听起来你想使用这个(未经测试):

shortsampleid = forms.ModelChoiceField(
    queryset=Checkin.objects.all(),
    to_field_name = 'shortsampleid',
    widget=forms.HiddenInput());
于 2011-08-29T20:20:23.407 回答