Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an object attribute value to an array Django

I am new to Django and this is my first project using it. I have run into an issue I don't understand and (perhaps I'm not using the right search terms) I'm not finding any relevant results in searching for solutions.

I was trying to get an array of distinct entries in the 'topic' field of my model. I was playing about in the shell, trying to figure this out when I got the following result which I didn't expect.

This is what I entered in the shell:

>>> from pomodoro.models import Chunk, Result
>>> Chunk.objects.all()
<QuerySet [<Chunk: Onboard State Estimation>, <Chunk: Newton's 2nd Law of Motion>, <Chunk: IF>]>
>>> a = []
>>> for q in Chunk.objects.all(): a += q.topic
...
>>> a
['R', 'o', 'b', 'o', 't', 'i', 'c', 's', 'M', 'e', 'c', 'h', 'a', 'n', 'i', 'c', 's', 'L', 'o', 'g', 'i', 'c']
>>> ose = Chunk.objects.get(pk=1)
>>> ose.topic
'Robotics'

I don't understand why I ended up with an array of individual letters rather than an array of the 'topic' strings. Can someone explain why this happened?

I'm also aware that there are much better ways of doing what I'm trying to do but, as a beginner, I haven't got to grips with Django properly.

like image 394
Era Avatar asked Nov 27 '25 17:11

Era


1 Answers

Try using the append method instead of a += q.topic

a.append(q.topic)

Or:

a += [q.topic]

The reason is that string objects are iterable and python will iterate over to append the items to your list. So iterating over 'Robotics' gives you ['R', 'o', 'b', 'o', 't', 'i', 'c', 's'].

Hence if you specify a single list value [q.topic] python will append the value of q.topic for each iteration in your for loop.

like image 85
slackmart Avatar answered Nov 30 '25 07:11

slackmart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!