简体   繁体   English

django中的下拉列表显示外键字段的对象

[英]drop down list in django shows object for foreign key field

I am using models to auto generate a form in Django. 我正在使用模型在Django中自动生成表单。 Here is my code 这是我的代码

class Dependent(models.Model):
    primarystudentid = models.ForeignKey('Students', models.DO_NOTHING, db_column='PrimaryStudentID')  # Field name made lowercase.
    dependentname = models.CharField(db_column='DependentName', max_length=100)  # Field name made lowercase.
    relation = models.CharField(db_column='Relation', max_length=50)  # Field name made lowercase.
    def __str__(self):
        return "{0}".format(self.primarystudentid)

primarystudentid is an auto generated field in Students table. primarystudentid是“学生”表中的一个自动生成的字段。 I have tried unicode and str. 我已经尝试了unicode和str。 But i am still getting the value of primarystudentid in dropdown as Students object. 但是随着学生的反对,我仍然在下拉菜单中获得了primarystudentid的价值。 I tried a lot of things from stack overflow and other sites but it doesn't seem to be working. 我从堆栈溢出和其他站点尝试了很多方法,但是似乎没有用。 Python version Python 2.7.13 Django version 1.9.13 Any help is appreciated! Python版本Python 2.7.13 Django版本1.9.13感谢您的帮助!

you need to reference the field in the other table. 您需要参考另一张表中的字段。

dep = Dependent.objects.first()
dep.primarystudentid.name # This would be the name

in your str example 在你的str例子中

def __str__(self):
    return "{0}".format(self.primarystudentid.name)

just worth noting that this can easily cause a lot of extra queries to be generated. 值得一提的是,这很容易导致产生大量额外的查询。

You need to update the str or unicode method of your Student table (not the Dependent table), and return name or whatever field you want to show in the dropdown. 您需要更新Student表(而不是Dependent表)的strunicode方法,并返回名称或要在下拉列表中显示的任何字段。

Example: 例:

class Student(models.Model):
    name = models.CharField(max_length=50)

def __str__(self):
    return u'{0}'.format(self.name)

PS: Please update the name of field dependentname to just name , because it is quite obvious that if this is in the Dependent model then it's the name of dependent. PS:请将字段dependentname的名称更新为just name ,因为很明显,如果这在Dependent模型中,则为dependent的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM