使用get_object_or_404 django失败

时间:2016-11-26 13:58:44

标签: python django django-models

这是代码:

>>> from shortener.models import KirrURL
>>> from django.shortcuts import get_object_or_404
>>> obj = get_object_or_404(KirrURL,shortcode='pric3e')

Traceback (most recent call last):File"/Users/phil/Desktop/django110/lib/python3.5/site
packages/django/shortcuts.py", line 85, in get_object_or_404
return queryset.get(*args, **kwargs)
File "/Users/phil/Desktop/django110/lib/python3.5/site-packages/django/db/models/query.py", line 385, in get
self.model._meta.object_name
shortener.models.DoesNotExist: KirrURL matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/phil/Desktop/django110/lib/python3.5/site-packages/django/shortcuts.py", line 93, in get_object_or_404
raise Http404('No %s matches the given query.' %     queryset.model._meta.object_name)
django.http.response.Http404: No KirrURL matches the given query.

>>> obj = KirrURL.objects.get(shortcode='pric3e')
>>> obj
<KirrURL: http://google.com>
>>> obj.id
1
>>> obj.url
'http://google.com'

我现在正在练习django模型。问题是当我使用get_object_or_404尝试获取与第二个关键字参数匹配的数据时它以某种方式失败。当我使用get()方法时。它成功了。我想我认为我应该在这里得到相同的结果。

#Model Class
class KirrURLManager(models.Manager):
    def all(self,*args,**kwargs):
        qs = super(KirrURLManager,self).all(*args,**kwargs)
        qs_main = qs.filter(active=False)
        return qs_main

    def refresh_shortcodes(self,items=None):
        qs = KirrURL.objects.filter(id__gte=1)
        if items is not None and isinstance(items,int):
            qs = qs.order_by('-id')[:items]
        for q in qs:
            q.shortcode = create_shortcode(q)
            q.save()
            print(q.id)
class KirrURL(models.Model):
    url = models.CharField(max_length=220,)
    shortcode = models.CharField(max_length=SHORTCODE_MAX,unique=True,blank=True)
    updated = models.DateTimeField(auto_now=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)
    objects = KirrURLManager()
    some_random = KirrURLManager()
    def save(self, *args, **kwargs):
        if self.shortcode is None or self.shortcode == "":
            self.shortcode = create_shortcode(self)
        super(KirrURL, self).save(*args, **kwargs)
    def __str__(self):
        return str(self.url)
    def __unicode__(self):
        return str(self.url)

2 个答案:

答案 0 :(得分:5)

我认为问题在于覆盖all()方法。 当您使用get_object_or_404()时,calling _get_queryset()函数返回manager.all()。但由于覆盖all()只返回非活动对象而get_object_or_404(KirrURL,shortcode='pric3e')的结果为空。

答案 1 :(得分:3)

您的自定义管理器产生的结果不一致,因为并不总是调用.all()。如果您希望此管理器始终过滤掉特定实例,则应覆盖get_queryset()。请务必在自定义管理器上方添加默认管理器,这样您仍然可以访问所有实例,例如:管理员。

class KirrURLManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(active=False)

class KirrURL(models.Model):
    objects = models.Manager() # default manager, put this one first
    custom = KirrURLManager()

现在KurrURL.objects.all()将返回所有实例(get_object_or_404(KirrURL, shortcode='pric3e')将能够找到您的实例),但您可以使用KirrURL.custom.all()访问所有非活动实例。