AttributeError:'QuerySet'对象没有'add'属性

问题描述:

我尝试定义一个函数,它将元素添加到一个新的空白查询集并返回它。我的函数的当前版本是这样的:AttributeError:'QuerySet'对象没有'add'属性

def get_colors(*args, **kwargs): 
    colors = Color.objects.none() 
    for paint in Paint.objects.all(): 
     if paint.color and paint.color not in colors: 
      colors.add(paint.color) 
    return colors 

我收到写着错误信息:

AttributeError: 'QuerySet' object has no attribute 'add'

为什么我不能添加元素到空查询集?我究竟做错了什么?

+1

见的:[如何创建一个空的查询集,并在Django手动添加的对象(http://*.com/questions/18255290/how-to-create-an-empty-queryset-and -to-add-objects-manually-in-django) – xyres

我不这么认为,你可以这样做。 QuerySet可以被认为是列表的扩展,但它不相同。

如果你需要返回颜色,你可以这样做。

def get_colors(*args, **kwargs): 
    colors = [] 
    for paint in Paint.objects.all(): 
     if paint.color and paint.color not in colors: 
      colors.append(paint.color) 
    return colors 
+0

这不起作用,因为'QuerySet'也没有'append'方法。发布前请先试用您的代码。 – xyres

+0

我不追加到查询集,而是列出。你有没有改变第二行? –

+0

对不起,我的坏!没有完全阅读你的代码!你应该在你的答案中提到你已经使用'list'而不是'QuerySet'来保存'colors'。无论如何,好的答案。 – xyres