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?

SamPassmore
  • 1,221
  • 1
  • 12
  • 32

2 Answers2

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] 
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • This breaks the serialisation line with "AttributeError: 'dict' object has no attribute '_meta'" – SamPassmore May 02 '18 at 13:35
  • This should help. https://stackoverflow.com/questions/46062242/queryset-serialize-attributeerror-dict-object-has-no-attribute-meta – Rakesh May 02 '18 at 13:37
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.

Chiefir
  • 2,561
  • 1
  • 27
  • 46