Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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'

Why can't I add elements to the empty queryset? What am I doing wrong?

like image 959
Dibidalidomba Avatar asked Mar 02 '26 23:03

Dibidalidomba


1 Answers

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.

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
like image 82
Bipul Jain Avatar answered Mar 04 '26 13:03

Bipul Jain