1

我有一个 Django 模型:

class ObservationMedia(models.Model):
    observation = models.ForeignKey(Observation)    
    audio_file = AudioFileField   ( upload_to=audio_dir, blank=True, null=True )
    photo_file = models.ImageField( upload_to=img_dir,   blank=True, null=True )

    def __unicode__(self):
        return "obsv-media "+str(self.pk)

其中观察是:

class Observation(GUIDModel):  
    guid = models.CharField(unique=True, max_length=36, default=uuid.uuid4)
    # many more fields here

是否有可能传递给的值ModelForm不是其主键而是字段?我想到的解决方案是制作主键。有可能避免这种情况吗?ObservationMediaObservationguidguid

4

1 回答 1

0

您可以执行以下操作,这并没有经过我目前能想到的测试。

class ObservationMediaForm(ModelForm):
    """ Observation Media Model Form """

    class Meta:
        model = models.ObservationMedia
        fields = ('observation', 'audio_file', 'photo_file')

    def __init__(self, *args, **kwargs):
        super(ObservationMediaForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['observation'].initial = models.Observation.objects.get(pk=self.instance.observation).guid
于 2013-03-22T10:53:30.067 回答