Django如何在单个模型实例上选择多个列
这似乎是我忽略了的一件简单的事情,但不管怎样,还是来了 我定义了一个模型,我想从模型中检索某些列(不是通过QuerySet API/model manager),而是在模型类中 例如:Django如何在单个模型实例上选择多个列,django,model,Django,Model,这似乎是我忽略了的一件简单的事情,但不管怎样,还是来了 我定义了一个模型,我想从模型中检索某些列(不是通过QuerySet API/model manager),而是在模型类中 例如: class mymodel(models.Model): col1 = ... col2 = ... col3 = ... def __unicode__(self): return '%s %s' % (self.col1, self.col3) # Notice I'm om
class mymodel(models.Model):
col1 = ...
col2 = ...
col3 = ...
def __unicode__(self):
return '%s %s' % (self.col1, self.col3) # Notice I'm omitting col2.
在\uuuu unicode\uuuu
类方法中,这至少算作2 DB查询。如何仅在1db查询中检索该类方法中的col1和col3?看起来应该很简单,我觉得我在做一些愚蠢的事情
更新:
根据反馈,我创建了一个测试模型、测试表单等。。。并发现一些用户所说的是正确的。但是,在我的实际代码(使用多种形式)中,更改\uuuuunicode\uuuu
方法以返回一列串联的值将SQL查询的数量从601更改为34。我只改变了那一行。根据我的测试用例,可能还有其他事情在进行,但重申一下,我只改变了unicode方法,得到了截然不同的DB点击量
我不确定我的其他代码是怎么回事,我必须试着仔细看看。同时,以下是测试用例,它们证明了你们的正确性:
# Models.py
class TestModelFK(models.Model):
col1 = models.CharField(max_length=8)
col2 = models.CharField(max_length=8)
col3 = models.CharField(max_length=8)
col4 = models.CharField(max_length=8)
allcols = models.CharField(max_length=32, blank=True, editable=False)
class Meta:
ordering = ('col1', 'col2')
def __unicode__(self):
return '%s %s %s %s' % (self.col1, self.col2, self.col3, self.col4)
def save(self, *args, **kwargs):
self.allcols = '%s %s %s %s' % (self.col1, self.col2, self.col3, self.col4)
super(TestModelFK, self).save()
class TestModel(models.Model):
quantity = models.IntegerField()
test_fk = models.ForeignKey(TestModelFK)
# forms.py
class TestModelForm(forms.ModelForm):
class Meta:
model = TestModel
# views.py
if request.method == 'GET':
post['TestModelFormSet'] = formset_factory(TestModelForm, extra=4)
\uuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法调用作为内存调用进行。它不会触发单独的数据库调用 我猜你在这么做
myModelInstance = MyModel.objects().get(id=1)
然后
print myModelInstance
>> "WhateverCol1is WhateverCol2is"
这绝对会触发1个数据库调用,因为您必须获取该模型实例。
这就是get()
所做的,它直接获取对象
由于您省略了字段声明,我猜col1
或col3
要么是manytomy
字段,要么是ForeignKey
,因此在获取实例时,它将获取字段引用的行
如果你有这样的查询集
myModelInstances = MyModel.objects().filter(id=1)
并对其进行迭代,它将对其进行评估,并需要n个数据库调用
QuerySet是惰性的,只有在某些事情发生时才进行计算(即转到数据库),这些事情是
- 在查询集上迭代
- 切片查询集
- 在查询集上使用
list()
- 使用
len()
- 使用
repr()
- 以及对查询集进行酸洗或缓存
阅读更多关于的信息让我们看看您的函数:
def __unicode__(self):
return '%s %s' % (self.col1, self.col3) # Notice I'm omitting col2.
当您调用
\uuuuuunicode\uuuuu
时,您的模型已经在内存中了。您可以从self
中访问任意多个字段,此时无法访问数据库。-1因为前提是false。您应该始终从\uuuuuuuunicode\uuuu
返回unicode对象,而不是字符串。很抱歉让您猜到了。直到我得到一些反馈,我才知道所有的信息。但总的来说,我是通过一个modelform中的choicefield调用\uuuuunicode\uuuu
方法的。如果您看到我的附加注释,我不确定为什么我要观察我看到的行为,因为我的测试用例无法再现我的实际代码所显示的问题。