" ...匹配查询不存在。"错误,但对象显然确实存在

时间:2018-05-01 14:09:09

标签: python django

我有lesson型号:

class Lesson(models.Model):
    list_name = models.CharField(max_length=50, primary_key=True)

    def __str__(self):
        return self.list_name

sound型号:

class Sound(models.Model):
    sound_hash = models.CharField(max_length=40, primary_key=True, editable=False)
    lessons = models.ManyToManyField(Lesson, verbose_name="associated lessons", related_name="words")

test_pair模型:

class TestPair(models.Model):
    master_sound = models.ForeignKey(Sound, related_name="used_as_master")
    user_sound = models.ForeignKey(Sound, related_name="used_as_user")

我的表单看起来像这样:

class SoundTestPairForm(ModelForm):
    user_sounds = forms.ModelMultipleChoiceField(Sound.objects.all())

    class Meta:
        model = TestPair
        fields = ['master_sound']

    def __init__(self, *args, **kwargs):
        super(SoundTestPairForm, self).__init__(*args, **kwargs)
        self.fields['master_sound'] = forms.CharField()
        self.fields['master_sound'].widget.attrs['readonly'] = 'readonly'

    def clean(self):
        cleaned_data = super(SoundTestPairForm, self).clean()
        if 'user_sounds' not in cleaned_data.keys():
            raise forms.ValidationError('You must select at least one sound to be compared')
        cleaned_data['master_sound'] = Sound.objects.get(pk=self.fields['master_sound'])
        return cleaned_data

这会引发DoesNotExist错误。追溯指向此行:cleaned_data['master_sound'] = Sound.objects.get(pk=self.fields['master_sound'])

本地变量如下:

self    

<SoundTestPairForm bound=True, valid=True, fields=(master_sound;associated_test;associated_lesson;user_sounds)>

cleaned_data    

{'associated_lesson': u'pooooooooooooooooooooooop',
 'associated_test': u'cats a',
 'master_sound': u'ad27ec5e0d048ddbb17d0cef0c7b9d4406a2c33',
 'user_sounds': [<Sound: Pants>]}

但是当我转到python manage.py shell并导入我的模型时: Sound.objects.get(pk=u'ad27ec5e0d048ddbb17d0cef0c7b9d4406a2c33') <Sound: oombah>

它击中了适当的对象。

这是我长期以来一直在处理的事情,而且令人沮丧。我尝试切换我的逻辑并最终导致DoesNotExist错误,无论我尝试什么。

有没有人有任何想法?

1 个答案:

答案 0 :(得分:3)

我认为你应该替换:

Sound.objects.get(pk=self.fields['master_sound'])

使用:

Sound.objects.get(pk=cleaned_data['master_sound'])

表单有效时,cleaned_data将包含其所有字段的键和值,您也可以在您的问题中看到(本地变量段落)。

一般来说,您应该使用单独的clean_<fieldname>方法进行验证。所以:

def clean_master_sound(self):
    master_sound_key = self.cleaned_data.get('master_sound')
    try:
        master_sound=Sound.objects.get(pk=master_sound_key)
    except Sound.DoesNotExist:
        raise forms.ValidationError("Sound with id: %s does not exist", master_sound_key)
    return master_sound