# Updating elastic django documents conditionally based on older documents

**URL:** <https://discuss.elastic.co/t/updating-elastic-django-documents-conditionally-based-on-older-documents/368922>\
**Category:** Elasticsearch\
**Created:** [October 16, 2024, 2:07pm UTC](https://discuss.elastic.co/t/updating-elastic-django-documents-conditionally-based-on-older-documents/368922 "2024-10-16T14:07:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Anshu\_Garg](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/anshu_garg/32/137533_2.png) [@Anshu\_Garg](https://discuss.elastic.co/u/Anshu_Garg)\
**Post date:** [October 16, 2024, 2:07pm UTC](https://discuss.elastic.co/t/updating-elastic-django-documents-conditionally-based-on-older-documents/368922/1 "2024-10-16T14:07:05Z")

</div>

Hi team, I am stuck on the below problem. Can somebody please help  
I am using django elasticsearch DSL and have below model structure and corresponding document

```auto
class Token(AppModel):
       # fields
       f1, f2, f3
class TokeDocument(Document):
       special_x = field
       special_y = field
       def prepare_special_x():
              # some computation not related to model instance
       def prepare_special_y():
              #some computation not related to model instance
       class DJango:
              model = Token
              fields = [f1, f2, f3]

```

I have a list of Token models say "model\_instances".  
I want to update all model\_instances to elasticsearch for above document. (I currently use TokenDocument().update(model\_instances, parallel=True, refresh=True))  
PROBLEM:  
Let's say I want to update special\_x and special\_y based on old values in the document (if it exists). How can we achieve that minimal latency?  
Let's say new document be new\_doc based on model\_instance in model\_instances and old\_doc be the corresponding old document, I want to update  
new\_doc.special\_x = new\_doc.special\_x if new\_doc.special\_x \> 0 else old\_doc.special\_x  
I tried fetching document in every prepare\_special\_\* functions and then updating conditionally but that would be very unoptimal I guess (because we query elastic servers multiple times which we should be able to reuse)  
I want to add the above functionality to all models in my project (will be creating a wrapper for it) for some globally specific fields
