我有以下模型,我正在尝试使用Django ModelForm的ModelChoiceField来快速解决我的问题
SO_SNDTIMEO
现在,当我尝试保存SettingsForm时,我得到了GameCode ='GameCode Object'而不是像Class Games(Model):
code = charField() # GTA, ABC, etc..
name = charField() # Grand Tourismo, ALL BBB CCC , etc..
unique_together(code, name)
class Settings(Model):
gameCode = charField(). #Didn't use Foreign key because of internal reasons where we can't use Games model somewhere outside
username = charField()
...
class GameCodeChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return obj.name
class SettingsForm(forms.ModelForm):
gameCode = GameCodeChoiceField(queryset=None,required=False)
class Meta:
model = Settings
fields = ['username']
def __init__(self, *args, **kwargs):
super(SettingsForm, self).__init__(*args, **kwargs)
self.fields['gameCode'].queryset = Games.objects.filter(game=game, isActive=True)
self.fields['gameCode'].to_field_name = 'code'
这样的代码..
请帮忙。编辑。
答案 0 :(得分:0)
to_field_name
更改生成的选项元素的值,而不是显示文本。
您要向模型添加__str__
方法。它将更改select元素中列出的每个对象实例的显示。
Class Games(Model):
code = charField() # GTA, ABC, etc..
name = charField() # Grand Tourismo, ALL BBB CCC , etc..
unique_together(code, name)
def __str__(self):
return self.code