我想列出保存在名为“ 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
2 回答
守着一只汪
TA贡献1872条经验 获得超3个赞
使用选项2,您可以尝试这种方式
related = Article.objects.filter(slug__icontains=slug).values('category').first()
if not related:
related = Article.objects.filter(category__icontains=slug).values('category').first()
添加回答
举报
0/150
提交
取消