简体   繁体   English

“……匹配查询不存在。”错误,但对象显然存在

[英]“… matching query does not exist.” error, but object clearly does exist

I have a lesson model: 我有一个lesson模型:

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

    def __str__(self):
        return self.list_name

A sound model: 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")

And a test_pair model: 和一个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")

My form looks something like this: 我的表单如下所示:

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

This is throwing a DoesNotExist error. DoesNotExistDoesNotExist错误。 The traceback points to this line: cleaned_data['master_sound'] = Sound.objects.get(pk=self.fields['master_sound']) 追溯指向此行: cleaned_data['master_sound'] = Sound.objects.get(pk=self.fields['master_sound'])

The local vars are as follows: 本地变量如下:

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>]}

But when I go to python manage.py shell , and import my model: Sound.objects.get(pk=u'ad27ec5e0d048ddbb17d0cef0c7b9d4406a2c33') <Sound: oombah> 但是当我转到python manage.py shell并导入我的模型时: Sound.objects.get(pk=u'ad27ec5e0d048ddbb17d0cef0c7b9d4406a2c33') <Sound: oombah>

It hits the appropriate object. 它击中了合适的物体。

This is something I've been dealing with for a long time, and it's super frustrating. 这是我已经处理了很长时间的事情了,这非常令人沮丧。 I try to switch my logic around and ultimately it ends up throwing a DoesNotExist error, regardless of what I try. 我尝试改变我的逻辑,最终不管我尝试什么,最终都会DoesNotExist错误。

Does anyone have any ideas? 有人有什么想法吗?

I think you should replace: 我认为您应该替换:

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

with: 有:

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

When the Form is valid, cleaned_data will include a key and value for all its fields and you can see that in your question as well (The local vars paragraph). 表单有效时, cleaned_data将在其所有字段中包含键和值,您也可以在问题中看到它(本地vars段落)。

In general speaking you should do validation in the individual clean_<fieldname> methods. 一般来说,您应该在单个clean_<fieldname>方法中进行验证。 So: 所以:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM