Django - One to One field bug not saving data without error

I am currently experiencing an issue with a one-to-one field in Django where the data was not stored after assigning value and save call is successful without any error occasionally. I'd say 60% of it was not saving and 40% is working. This only happens on our production server where there are millions of rows for Model1 and Model2 and there are so many processes ongoing.

# models.py
class Model1(models.Model):
    field1 = models.OneToOneField(Model2, on_delete=models.SET_NULL, null=True, blank=True, default=None) 
    # Some other fields here
   
    def link_item(self, model2_id):
        field1 = Model2.objects.get(id=model2_id)
        self.field1 = field1
        self.save()

# views.py
import module

def my_view(requests):
    model1_obj = Model1.objects.get(id=model1_id)
    result = module.another_function(model1_obj, request_data)
    return result

# module.py
def another_function(model1_obj, request_data):
    if request_data['status'] == 'complete':
        model1_obj.link_item(request_data['model2_id'])

I tried logging the values of self.field1 after the self.save call and I see the model2 object is displayed.

Any possible reason why it happens sometimes?

Back to Top