Dibidalidomba
Dibidalidomba

Reputation: 777

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'

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

Upvotes: 3

Views: 5708

Answers (1)

Bipul Jain
Bipul Jain

Reputation: 4643

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

Upvotes: 4

Related Questions