django 1.5.1错误DoesNotExist:MyModel匹配查询不存在,但存在

时间:2013-07-30 14:45:08

标签: django django-models django-views

我的观点:

try:
    id_osirix = int(request.POST.get('id'))
except ValueError:
    return HttpResponseBadRequest(_('ID is not numeric'))

instance = Osirix.objects.get(pk=id_osirix)      
url = instance.url 
instance.delete()    

# Reload MyModel code using url var

但我有这个错误:DoesNotExist:MyModel匹配查询不存在。查找参数是{u'id__exact':3}

如果我评论

#    url = instance.url

它可以工作并删除记录。

MyModel类定义

# base/models.py
from django.db import models

class TimeStampedModel(models.Model):
    """
    An abstract base class model that provides selfupdating
    created and modified fields.
    """    
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

# apps/myapp/models.py
class OsirixType(models.Model):  
    name = models.CharField(max_length=255, help_text=_('Standards list'))
    description = models.TextField(blank=True)

    class Meta:
        verbose_name = _("Osirix type")
        verbose_name_plural = _("OsirixType multiple types")

    # On Python 3: def __str__(self):
    def __unicode__(self):
        return self.name


# apps/myapp/models.py
class Osirix(TimeStampedModel):
    """    
    """
    owner = models.ForeignKey(User)
    type = models.ForeignKey(OsirixType)
    title = models.CharField(max_length=255)        
    keywords = TaggableManager(_('Keywords'), blank=True, help_text=_('Commonly used word(s)'))
    operations = models.TextField(_('Operations'), blank=True)
    url = models.URLField(verbose_name=_("URL"))    
    version = models.CharField(        
        max_length=20,
        default='0.0.0',)

    class Meta:
        verbose_name = _("Osirix connection")
        verbose_name_plural = _("Osirix multiple connections")

    # On Python 3: def __str__(self):
    def __unicode__(self):
        return self.title

    @property
    def ttd(self):
        from apps.fm.layers.models import Layer        
        return str(Layer.objects.filter(Osirix=self.id).aggregate(Avg('ttd'))['ttd__avg'])

    def keyword_list(self):
        keywords_qs = self.keywords.all()
        if keywords_qs:
            return ','.join([kw.name for kw in keywords_qs])
        else:
            return ''

@receiver(post_delete, sender=Osirix)
def osirix_post_delete_handler(sender, **kwargs):
    osirix = kwargs['instance']    
    osirix = os.path.join(THUMBNAILS_ROOT, str(osirix.pk // DATA_PARTITION), str(osirix.pk)) + '/'
    shutil.rmtree(osirix_thumbnail_root, ignore_errors=True)

如果我评论上一行(url = instance.url)

,它会按预期工作

想法? 工作流程是否正确?

1 个答案:

答案 0 :(得分:4)

我不明白为什么评论该行会使它工作但是你应该抓住那个错误:

try:
    id_osirix = int(request.POST.get('id'))
except ValueError:
    return HttpResponseBadRequest(_('ID is not numeric'))

try:
    osirix = Osirix.objects.get(pk=id_osirix)
except Osirix.DoesNotExist:  # catch the DoesNotExist error
    osirix = None

if osirix:  # delete if only exists
    url = osirix.url
    osirix.delete()