代码之家  ›  专栏  ›  技术社区  ›  hekevintran

Django数据库缓存

  •  2
  • hekevintran  · 技术社区  · 16 年前

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

    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方法返回对象本身,这样就可以避免第二次 获取() 获取()

    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
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Daniel Roseman    16 年前

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

    (第一个片段实际上包含一个错误,因为clean方法没有返回任何内容,所以 id_a

        2
  •  0
  •   Matthias Kestenholz    16 年前

    未缓存此查询。get()调用从来都不是。另一方面,查询集(有时)在第一次求值之后缓存。

    推荐文章