Python 属性错误:';QuerySet';对象没有属性';添加';

Python 属性错误:';QuerySet';对象没有属性';添加';,python,django,Python,Django,我尝试定义一个函数,将元素添加到新的空查询集并返回它。my函数的当前版本如下所示: 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 co

我尝试定义一个函数,将元素添加到新的空查询集并返回它。my函数的当前版本如下所示:

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”对象没有属性“add”


为什么我不能向空的queryset添加元素?我做错了什么

我认为你不能这样做。 QuerySet可以被认为是list的扩展,但它是不同的

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

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

请注意:这将不起作用,因为
QuerySet
也没有
append
方法。请在发布前试用您的代码。我不是附加到queryset,而是附加到列表。你换第二行了吗?对不起,我的错!没有完全阅读你的代码!您应该在回答中提到,您使用了
列表
而不是
查询集
来保存
颜色
。好答案,谢谢你们两位。我只是希望有一种使用QuerySet的方法。好吧,我会用一个列表来代替。