SamPassmore
SamPassmore

Reputation: 1365

Django: Add a list to a QuerySet

I am new to django so apologies if this is not possible or easy.

I have a view that takes a subset of a model

data = Terms.objects.filter(language = language_id)

The subset is one language. The set has a number of concepts for a language. Some languages might use the same word for multiple concepts, and I want to colour these the same in an SVG image. So I do this next:

for d in data:
    if d.term is None:
        d.colour = "#D3D3D3"
    else:
        d.colour = termColours[d.term] 

Where termColours is a dictionary with keys as the unique terms and values as the hexadecimal colour I want.

I thought this would add a new colour attribute to my queryset. However, when I convert the queryset to json (in order to pass it to JS) the colour object is not there.

    terms_json = serializers.serialize('json', data)

How can I add a new colour element to my queryset?

Upvotes: 1

Views: 389

Answers (2)

Chiefir
Chiefir

Reputation: 2671

If I understand correctly - you need Django ORM annotation. And it might look like that:

from django.db.models import Case, When, Value

data = Terms.objects.filter(language = language_id)
                     .annotate(color = Case(
                               When(term__isnull = True, then = "#D3D3D3"),
                               When(term__isnull = False, then = termColours[Value(term)]),)) 

Only problem here - I don't exactly know this moment - termColours[Value(term)], you need to test different combinations of that expressions to get the value of field term.

Upvotes: 0

Rakesh
Rakesh

Reputation: 82785

Convert your Queryset to Dict and then modify values.

Ex:

data = Terms.objects.filter(language = language_id).values()
for d in data:
    if d.term is None:
        d.colour = "#D3D3D3"
    else:
        d.colour = termColours[d.term] 

Upvotes: 1

Related Questions