Skip to main content
 首页 » 编程设计

python之Django 数据库缓存

2025年05月04日36youxin

我有一个 Django 表单,它使用整数字段通过主键查找模型对象。该表单有一个 save() 方法,该方法使用整数字段引用的模型对象。模型管理器的 get() 方法被调用两次,一次在 clean 方法中,一次在 save() 方法中:

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 

我不确定这是两次还是一次访问数据库,所以我在 clean 方法中返回了对象本身,这样我就可以避免第二次 get() 调用。调用 get() 会访问数据库两次吗?还是对象缓存在线程中?

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 

请您参考如下方法:

不,该值不会被缓存。你的第二个例子是正确的方法。

(第一个片段实际上包含一个错误,因为 clean 方法没有返回任何内容,所以 id_a 属性最终会为空。)