开发者

Django: Save Modelform with Foreignkey using to_field and ModelChoiceForm

I have a problem saving a ModelForm when using a foreign key that doesn't "point" to the primary key of it's related table (legacy schema woes) I am using to_field= for my Foregin Key so that it will be related to a key that is not exactly a key. My ModelForm foreignkey uses a ModelChoiceField with a queryset and a widget of HiddenInput() because the default rendering takes 2 minutes. I get an invalid choice when I try to save because the queryset returns开发者_Python百科 the primary key as the option value when returning the related object (Checkin). How can I still use ModelChoiceField with this setup? My basic schema below.

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'


ModelChoiceField has an undocumented to_field_name parameter that you can pass in at construction time, which makes it use that field instead of the primary key.

It sounds like you want to use this (untested):

shortsampleid = forms.ModelChoiceField(
    queryset=Checkin.objects.all(),
    to_field_name = 'shortsampleid',
    widget=forms.HiddenInput());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜