简体   繁体   English

AttributeError:“ QuerySet”对象没有属性“ add”

[英]AttributeError: 'QuerySet' object has no attribute 'add'

I try to define a function that adds elements to a new, empty queryset and returns it. 我尝试定义一个将元素添加到新的空查询集并返回它的函数。 The current version of my function looks like this: 我的函数的当前版本如下所示:

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

I get the error message that says: 我收到以下错误消息:

AttributeError: 'QuerySet' object has no attribute 'add' AttributeError:“ QuerySet”对象没有属性“ add”

Why can't I add elements to the empty queryset? 为什么不能将元素添加到空查询集中? What am I doing wrong? 我究竟做错了什么?

I don't think so you can do it like this. 我不认为您可以这样做。 QuerySet can be thought of as an extension of list but it is not the same. 可以将QuerySet视为list的扩展,但它并不相同。

If you need to return the colors you can do it like this. 如果您需要返回颜色,可以这样进行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM