Django中的外键问题

时间:2011-01-31 14:20:37

标签: django django-models django-forms

我正在尝试创建一个与ForeignKey链接的表单。

Model.py

    enter code here
    model.py

class CreateD(models.Model):
    id=models.IntegerField(primary_key=True)
    db = models.CharField(max_length=50, blank=True)
    iss  = models.CharField(max_length=100, blank=True)
    status = models.CharField(max_length=2, blank=True ,default='A')
    class Meta:
        db_table = u'add_d'

    def __unicode__(self):
        return u'%s %s' % (self.db,self.iss)


class Assignment(models.Model):
    id = models.IntegerField(primary_key=True)
    assign_to = models.CharField(max_length=50, blank=True)
    db_name = models.ForeignKey(CreateDb,related_name='set__dbname')
    issue_type = models.ForeignKey(CreateDb,related_name='set_issuetype')
    date = models.DateTimeField(null=True, blank=True)
    class Meta:
        db_table = u'assignment'
    def __unicode__(self):
        return u'%s %s' % (self.db_name,self.issue_type)

form.py

class AssignmentForm(ModelForm):


class Meta:
    model = Assignment
    exclude = ('id','date','assign_to')


assign.html 

   {{forms.as_p}}


Data in the sql :
   id  db iss
   1   A   AB
   2   B   BA




Output genrated from html page is 

   db_name    : A AB (choice field)
                B BA
   issue_type : A AB (choice field)
                B BA


Actually i Need a output like below in html:

    db_name    : A (choice field)
                 B 
   issue_type : AB (choice field)
                BA

请帮我这个............

1 个答案:

答案 0 :(得分:1)

如果我的问题正确您想要更改选择框中的标签,默认情况下它们是通过模型的__unicode__方法生成的,但您可以覆盖表单字段的label_from_instance方法并选择另一种方法;见Django forms: how to dynamically create ModelChoiceField labels