如何解决查询500中的错误500?

我想列出保存在名为“ related”的数据库字段中的相关类别


我的代码


def category(request, slug):

    related = Article.objects.filter(slug__icontains=slug).values('related').first()


return render(request,'category.html',{'related':related}

y尝试:


选项1:如果有退货,则相关无我仅分配类别


Article.objects.filter(Q(slug__icontains=slug) | Q(category__icontains=slug))

选项2:


if related is None:

    related = Article.objects.filter(category__icontains=slug).values('category').first()    

else:

    related = related.get('related').split(',')

错误:


'NoneType'对象没有属性'get'


在我的数据库中,我检查了以下查询:


SELECT * FROM `article` WHERE slug like '%internet%'

而且我得到0条记录,所以错误是连贯的,但是在这种情况下我看不到如何分配


SELECT * FROM `article` WHERE category like '%internet%'

我有22个结果


模型:


class Article(models.Model):

    category = models.CharField(max_length=2000, blank=True, null=True)

    related = models.CharField(max_length=2000, blank=True, null=True)

    text = models.CharField(max_length=2000, blank=True, null=True)

    slug= models.SlugField(max_length=255, unique=True)

    class Meta:

        managed = False

        db_table = 'article'

    def __str__(self):

        return u'%s %s %s %s' % (self.categoria,self.related, self.text, self.slug)

选项3:


Article.objects.filter(Q(slug__icontains=slug) | Q(category__icontains=slug)).values_list("related", flat=True).distinct()

错误太多值以至于无法解包(预期2)


错误行37与此:


relateds = related.get('related')。split(',')


所有过程:


def category(request, slug):


    related = Article.objects.filter(Q(slug__icontains=slug) | Q(category__icontains=slug)).values('related').distinct()


temp=[]

    for x in relateds:

        temp.append(x.replace(" ","-").replace("é","e"))

    relateds=temp


小唯快跑啊
浏览 174回答 2
2回答

守着一只汪

使用选项2,您可以尝试这种方式related = Article.objects.filter(slug__icontains=slug).values('category').first()  if not related:    related = Article.objects.filter(category__icontains=slug).values('category').first()  
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python