1

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?

2
  • Could you explain why this would help? Commented May 2, 2018 at 13:27
  • .values() will turn your queryset into a list of dictionaries. As such, they can be modified as you please. Commented May 2, 2018 at 13:34

2 Answers 2

1

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] 
Sign up to request clarification or add additional context in comments.

2 Comments

This breaks the serialisation line with "AttributeError: 'dict' object has no attribute '_meta'"
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.