[英]Django: Getting foreign key value to show in forms
我一直在用我的測試應用程序研究django並在其中玩耍,我想就此事尋求幫助。
我有以下型號:
class Job_Posting(models.Model):
Job_Position = models.CharField(max_length=30, null=True, unique=True)
def __unicode__(self):
return self.Job_Position
class Courses_list(models.Model):
Abbreviation = models.CharField(max_length=100, unique=True)
Course = models.CharField(max_length=100, unique=True)
def __unicode__(self):
return self.Abbreviation
class Educational_Requirement(models.Model):
fkey = models.ForeignKey('Job_Posting')
Course = models.ForeignKey('Courses_list')
在管理員中,這很簡單,可以添加職位並分配所需的課程。 我的問題是與Educational_Requirement
因為我在通過形式的我前端顯示它ModelChoiceField
並重寫queryset
,以顯示正確的選擇。
下拉顯示的Educational_Requirement object
,我希望它顯示Educational_Requirement
中Course
的值。 我不能在Educational_Requirement
使用__unicode__
,因為它會返回錯誤:
coercing to Unicode: need string or buffer, Courses_list found
我真的需要在Educational_Requirement
設置__unicode__
並添加字符串字段嗎? 我不能這樣做,因為它確實會破壞我這樣做的目的,或者是否有更好的方法來實現? 非常感謝。
如果您有任何新手提示,請隨時發表評論,我們將不勝感激。
如果要更改ModelChoiceField
的顯示值,則可以輕松定義自己的字段並覆蓋label_from_instance
方法:
class CourseField(forms.ModelChoiceField):
def label_from_instance(self, obj):
# return the field you want to display, which is Course
return obj.Course
class EducationalRequirementForm(forms.ModelForm):
Course = CourseField(queryset=Courses_list.objects.all())
沒有關系,但是您正遭受一些不良的編碼風格的困擾。 模型是python類,因此它們應該類似於EducationalRequirement
。 字段是python類的屬性,它們應使用小寫,並帶有下划線,例如job_position
。 查看python PEP8文檔以獲取更多代碼樣式信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.