Home > Net >  How can I add an attribute to a queryset in Django
How can I add an attribute to a queryset in Django

Time:05-19

I've got a Django 2.2.28 legacy application running under Python 3.7.7. I've got a queryset I'd like to add data to that's not from the database, but generated by Python. So something like this:

for item in queryset.iterator():
    item.new_property = python_generated_property_value()

I want this new_property to be available in a template. Any suggestions/ideas would be greatly appreciated!

CodePudding user response:

I think first you should add new_property field to your Item model and then you can add the value. If this is the case you might want to it this way:

for item in queryset.iterator():
item.new_property = python_generated_property_value()
item.save()

After, in your template you could display it in such a way: {{ item.new_property }}

CodePudding user response:

you can create a dictionary, and pass data in a template with it

new_dict = {}
for item in queryset.iterator():
    new_dict["item_property"] = python_generated_property_value()
    

this will give you a dictionary in a same order as it is in your queryset, and you could "for loop" this dict in parallel with your queryset in a template

  • Related