Gex*_*xas 1 python django django-models python-3.x
我正在尝试学习 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
Run Code Online (Sandbox Code Playgroud)
现在views.py我想根据用户输入进行一些计算。用户将从第一个字段 ( Country) 中选择值,我需要基于此找到第二个字段值 ( PPP)。
这意味着我的数据结构是这样的:
Country | PPP
----------------
Lithuania | 0.45
Germany | 0.86
Estonia | 0.55
Spain | 0.77
Run Code Online (Sandbox Code Playgroud)
所以我会知道国家,我需要访问它的 PPP。我该怎么做?
因为我尝试过的各种解决方案给了我一个错误。
我累了的 Lats 解决方案:
pVal = str(form.cleaned_data['Country'])
country = Countries.objects.first()
pValKof = getattr(country, pVal)
Run Code Online (Sandbox Code Playgroud)
根据我的研究,我觉得我应该接近解决方案,但我无法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
Run Code Online (Sandbox Code Playgroud)
编辑:更改了我的解决方案,因为我错过了表单字段是 ModelChoiceField 的事实
代替:
pVal = str(form.cleaned_data['Country'])
country = Countries.objects.first()
pValKof = getattr(country, pVal)
Run Code Online (Sandbox Code Playgroud)
做这个:
country = form.cleaned_data['Country']
ppp = country.PPP
Run Code Online (Sandbox Code Playgroud)
此外:
Python 中的属性应以小写字母开头,类以大写字母开头,因此不要使用 Country 和 PPP,而是使用 country 和 ppp(不确定 ppp 代表什么,使用更具描述性的名称不会有什么坏处)
型号名称应为单数。所以,而不是国家,使用国家
属性 Country 可能更具描述性。尝试使用名称而不是国家。
我会为每个国家/地区选择一个唯一的名称。
所以要清理一下你的代码:
class Country(models.Model):
name = models.CharField(max_length=200, unique=True, null=False)
ppp = models.DecimalField(max_digits=15, decimal_places=10)
def __str__(self):
return self.name
Run Code Online (Sandbox Code Playgroud)
和
country = form.cleaned_data['country']
ppp = country.PPP
Run Code Online (Sandbox Code Playgroud)
和表单文件:
class PGPskaiciuokle(forms.Form):
country = forms.ModelChoiceField(queryset=Country.objects.all(),
label="Choose country")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |