【发布时间】:2020-01-08 06:28:15
【问题描述】:
我正在尝试学习 django,但在访问模型时遇到了问题。
我在models.py 中的模型如下所示:
class Countries(models.Model):
Country = models.CharField(max_length=200)
PPP = models.DecimalField(max_digits=15, decimal_places=10)
def __str__(self):
return self.Country
现在在views.py 我想根据用户输入进行一些计算。用户将从第一个字段 (Country) 中选择值,我需要在此基础上找到第二个字段值 (PPP)。
这意味着我的数据结构如下:
Country | PPP
----------------
Lithuania | 0.45
Germany | 0.86
Estonia | 0.55
Spain | 0.77
所以我会知道国家,我需要访问它的 PPP。我该怎么做?
因为我尝试的各种解决方案都会出错。
我厌倦了 Lats 解决方案:
pVal = str(form.cleaned_data['Country'])
country = Countries.objects.first()
pValKof = getattr(country, pVal)
根据我的研究,我觉得我应该接近解决方案,但我无法完全理解 getattr。或者也许还有其他方法可以实现这一点?
编辑:这是我的forms.py 的相关部分
class PGPskaiciuokle(forms.Form):
country = forms.ModelChoiceField(queryset=Countries.objects.all(),
label="Choose country")
def clean_country(self):
country = self.cleaned_data['country']
return country
【问题讨论】:
-
请张贴您的forms.py
-
添加了相关部分,抱歉我认为这与问题无关。
标签: python django python-3.x django-models