简体   繁体   English

Django数据库缓存

[英]Django database caching

I have a Django form that uses an integer field to lookup a model object by its primary key. 我有一个Django表单,该表单使用整数字段通过其主键查找模型对象。 The form has a save() method that uses the model object referred to by the integer field. 该表单具有一个save()方法,该方法使用整数字段所引用的模型对象。 The model's manager's get() method is called twice, once in the clean method and once in the save() method: 模型管理者的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

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. 我不确定这是两次还是一次命中数据库,所以我用clean方法返回了对象本身,这样就避免了第二次get()调用。 Does calling get() hit the database two times? 调用get()是否两次击中数据库? 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

No, the value wouldn't be cached. 不,该值不会被缓存。 Your second example is the right way to go. 您的第二个示例是正确的方法。

(The first snippet actually contains an error, in that nothing is returned from the clean method, so the id_a attribute would end up empty.) (第一个代码段实际上包含一个错误,因为clean方法未返回任何内容,因此id_a属性最终将为空。)

This query is not cached. 此查询未缓存。 get() calls never are. get()调用永远不会。 QuerySets on the other hand, are (sometimes) cached after the first evaluation. 另一方面,(有时)在第一次评估后缓存QuerySet。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM