Django database caching

Posted by hekevintran on Stack Overflow See other posts from Stack Overflow or by hekevintran
Published on 2010-04-16T06:58:21Z Indexed on 2010/04/16 7:03 UTC
Read the original article Hit count: 288

Filed under:
|
|

I have a Django form that uses an integer field to lookup a model object by its primary key. The form has a save() method that uses the model object referred to by the integer field. The model's manager's get() method is called twice, once in the clean method and once in the save() method:

class MyForm(forms.Form):
    id_a = fields.IntegerField()

    def clean_id_a(user_id):
        id_a = self.cleaned_data['id_a']
        try:
            # here is the first call to get
            MyModel.objects.get(id=id_a)
        except User.DoesNotExist:
            raise ValidationError('Object does not exist')

    def save(self):
        id_a = self.cleaned_data['id_a']
        # here is the second call to get
        my_model_object = MyModel.objects.get(id=id_a)

        # do other stuff

I wasn't sure whether this hits the database two times or one time so I returned the object itself in the clean method so that I could avoid a second get() call. Does calling get() hit the database two times? Or is the object cached in the thread?

class MyForm(forms.Form):
    id_a = fields.IntegerField()

    def clean_id_a(user_id):
        id_a = self.cleaned_data['id_a']
        try:
            # here is my workaround
            return MyModel.objects.get(id=id_a)
        except User.DoesNotExist:
            raise ValidationError('Object does not exist')

    def save(self):
        # looking up the cleaned value returns the model object
        my_model_object = self.cleaned_data['id_a']

        # do other stuff

© Stack Overflow or respective owner

Related posts about python

Related posts about django