我想列出保存在名为“ 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
答案 0 :(得分:0)
使用选项2,您可以尝试这种方式
related = Article.objects.filter(slug__icontains=slug).values('category').first()
if not related:
related = Article.objects.filter(category__icontains=slug).values('category').first()
答案 1 :(得分:0)
如果我正确理解了您想做什么,则可以将options 1与values_list方法一起使用。
Article.objects.filter(Q(slug__icontains=slug) | Q(category__icontains=slug)).values_list("related", flat=True).distinct()
此查询将返回您搜索的子弹的所有唯一相关字段。您还可以通过related__isnull=False
views.py文件最终应如下所示。我已经纠正了错字和缩进。
def category(request, slug):
if slug is None:
related = Article.objects.filter().values_list('related', flat=True).distinct()
else:
related = Article.objects.filter(Q(slug__icontains=slug) | Q(category__icontains=slug)).values_list('related', flat=True).distinct()
relateds=[]
for x in related:
relateds.append(x.replace(" ","-").replace("é","e"))
return render(request,'category.html',{'related': relateds})