[英]Django View/Model Attribute Error
I'm new to Django and I'm in the process of converting a PHP project into Python etc. 我是Django的新手,正在将PHP项目转换为Python等。
I'm trying to do something super simple, but I keep getting the following error: 我正在尝试做一些超级简单的事情,但我不断收到以下错误:
AttributeError at /news/1/
'QuerySet' object has no attribute 'slug'
Here is my most of my Model to help explain: 这是我大部分的模型来帮助解释:
class Article(models.Model):
title = models.CharField(max_length=200)
STATUS_CHOICES = ((1,'Published'), (2,'Hidden'), (3,'Draft'))
status = models.IntegerField(choices=STATUS_CHOICES,default=3)
pub_date = models.DateField('date published')
tags = TaggableManager()
header_width = models.IntegerField(default=1,blank=True,null=True)
header_height = models.IntegerField(default=1,blank=True,null=True)
header = models.ImageField(upload_to='news/',width_field='header_width',height_field='header_height',blank=True,null=True)
header_filter = models.BooleanField('Enable filter',default=1)
excerpt = HTMLField(blank=True)
body = HTMLField(blank=True)
custom_link_text = models.CharField(max_length=20,default="Read More")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
slug = AutoSlugField(unique=True,max_length=200,populate_from='db_slug',default="",slugify=return_value)
def __str__(self):
return self.title
Im currently just testing to pull through the slug, so my view method currently looks like this: 我目前只是在测试以通过子弹,所以我的view方法目前看起来像这样:
def detail_redirect(request, pk):
a = Article.objects.all().filter(pk=pk)
return HttpResponse(a.slug)
# return redirect('news:detail',args=(a.slug,pk))
The plan is for this method to redirect to another URL in my application. 该方法的计划是将该方法重定向到我的应用程序中的另一个URL。 It queries the DB via the primary key and fetches the Slug, which I then pass on to the redirect shortcut. 它通过主键查询数据库并获取Slug,然后我将其传递给重定向快捷方式。
It seems to be something that should just work, but it's not. 这似乎应该起作用,但事实并非如此。 It's really frustrating. 真令人沮丧。 The object i query appears to return ok. 我查询的对象似乎返回确定。 Because of my __str__ method it returns the title. 由于我的__str__方法,它返回标题。 But any other attributes throw and error. 但是其他任何属性都会引发错误。 Could it be todo with visibility such as being private or protected? 可以与私有或受保护之类的知名度相提并论吗?
I'm hoping it's something simple I'm missing. 我希望这是一个简单的东西,我想念了。 Let me know if you require more code/detail to help explain. 让我知道您是否需要更多代码/细节来帮助解释。
Thanks for taking the time to look at my question. 感谢您抽出宝贵时间来查看我的问题。
filter
always returns a queryset, which is a list-like object potentially consisting of many items. filter
始终返回一个查询集,这是一个可能由许多项目组成的类似列表的对象。 Querysets do not have model attributes, only their members do. 查询集不具有模型属性,只有其成员具有。 You should use get
instead: 您应该使用get
代替:
a = Article.objects.get(pk=pk)
(Note you don't need all()
, in either version of the code.) (请注意,在任一版本的代码中都不需要all()
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.