Home > Mobile >  How can I add a field to a queryset and populate it within a loop?
How can I add a field to a queryset and populate it within a loop?

Time:10-11

I have a queryset foo that contains a couple thousand items. Now I would like to add a field bar to this queryset whose value depends on some logic embedded in a loop. So I want to iterate foo and enrich bar for each item.

# Views.py

def example(request):

    [..]

    # Create `Bar` field for queryset
    foo.annotate(bar='')

    # Iterate queryset
    for item in foo:

        [..] # logic that returns a string
 
            # Populate field 'bar'
            item.bar = 'example_string'

However, it already breaks at foo.annotate(bar='') returning

QuerySet.annotate() received non-expression(s): .

CodePudding user response:

If you want to annotate with a non-empty string you can sue:

from django.db.models import Value

foo.annotate(bar=Value(''))

That being said, it makes not much sense to annotate with an empty string, you simply set an attribute on your Foo objects. I would also advise to wrap the items in a list, since subscripting will otherwise make new database queries.

  • Related