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'
为什么我不能添加元素到空查询集?我究竟做错了什么?
答
我不这么认为,你可以这样做。 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
见的:[如何创建一个空的查询集,并在Django手动添加的对象(http://*.com/questions/18255290/how-to-create-an-empty-queryset-and -to-add-objects-manually-in-django) – xyres