3

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?

Dibidalidomba
  • 757
  • 6
  • 17
  • 1
    See this: [how to create an empty queryset and to add objects manually in django](http://stackoverflow.com/questions/18255290/how-to-create-an-empty-queryset-and-to-add-objects-manually-in-django) – xyres Feb 28 '17 at 14:30

1 Answers1

4

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
Bipul Jain
  • 4,523
  • 3
  • 23
  • 26
  • This won't work because `QuerySet` doesn't have the `append` method as well. Please try out your code before posting. – xyres Feb 28 '17 at 14:39
  • I am not append to queryset but to list. Have you changed the second line ? – Bipul Jain Feb 28 '17 at 14:40
  • Sorry, my bad! Didn't quite read your code! You should mention that in your answer that you've used `list` instead of a `QuerySet` to hold `colors`. Good answer, anyway. – xyres Feb 28 '17 at 14:42
  • Thanks to both of you. I was just hoping there is a way to do it using QuerySet. Well, I will just use a list instead. – Dibidalidomba Feb 28 '17 at 14:45