我有一個Django窗體,它使用整數字段通過主鍵查找模型對象。該表格有一個save()
方法,該方法使用由整型字段引用的模型對象。該模型的經理的get()
方法被調用了兩次,一次是在清潔的方法,一次在save()
方法:Django數據庫緩存
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
我不知道這是否訪問數據庫兩次或一次,所以我返回的對象本身乾淨的方法,以便我可以避免第二個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
在這種情況下,是我避免了第二個電話的方式好如何做到這一點?或者是否有規範的Django方法來執行此操作? – hekevintran 2010-04-16 07:12:07
帶查詢集所有不可調用字段值都被緩存,而可調用字段值不是 – satoru 2010-04-16 07:23:44
@ Satoru.Logic什麼是可調用字段值?你怎麼稱呼一個價值? – hekevintran 2010-04-16 07:49:24