Comment

Paulo Almeida

You don't need the for loop, right? You can pass the django query directly to ''.join.

Replies

Peter Bengtsson

See James's comment below.

There are even faster ways but if you really really need the list of values into python, to do something the database can't do, then this story is relevant.

Paulo Almeida

I didn't mean to imply the story wasn't relevant, on the contrary, since what I said only applies to f4. It's a bonus of that solution that you could forgo the for loop entirely. I wasn't even thinking about speed, just readability. You get something you can iterate over as a list, with values_list and flat=True, but even if you wanted an actual list, you could just call list() on it, with no need for the loop.

That said, I wasn't aware of StringAgg, James's solution is indeed awesome.

Chris Foresman

I came to say the same; at the very least this would be much cleaner.

```
def f4(a):
    names = Song.objects.filter(artist=a).values_list("name", flat=True):
    return hashlib.md5("".join(list(names)).encode("utf-8")).hexdigest()
```

Peter Bengtsson

That is no different. Just styled differently.