models.py
class userdetails(models.Model):
userid=models.IntegerField(unique=True)
firstname=models.CharField(max_length=100,null=False,blank=False)
lastname=models.CharField(max_length=100,null=True,blank=True)
emailid=models.CharField(max_length=500,null=False,blank=False)
def __unicode__(self):
return self.firstname
class studdetails(models.Model):
total=models.CharField(max_length=500)
fkid=models.IntegerField()
def __unicode__(self):
return self.userdetails.firstname
我试图获取userdetails表的名字字段,其中studdetails.fkid = userdetails.userid。任何人都可以帮忙吗?请!
答案 0 :(得分:2)
尽量不要手动处理外键和ids
使用模型的ForeignKey
列类型与外表/模型相关联
试试这个:
class User(models.Model):
first_name = models.CharField(max_length=100,null=False,blank=False)
last_name = models.CharField(max_length=100,null=False,blank=False)
email_address = models.CharField(max_length=500,null=False,blank=False)
def __unicode__(self):
return self.firstname
class Student(models.Model):
total = models.CharField(max_length=500)
user = models.ForeignKey('User')
def __unicode__(self):
return self.user.firstname
答案 1 :(得分:0)
感谢您的回复,我得到了结果,使用以下代码。
def __unicode__(self):
try:
ud = User.objects.get(userid=self.fkid)
return u'%s - %s -%s' %(ud.first_name , ud.last_name ,ud.email_address)