繁体   English   中英

在 django model 外键未检索实际值

[英]in django model foreign key not retrieving actual value

in django i defined two tables 1. country 2.state while i am trying to print country_id from State table its retriving like "State object (1)" i am expectin number alone like 1,2 3

    # location lookup 
class Country(models.Model):
    country_id=models.AutoField(auto_created=True,primary_key=True)
    country_name=models.CharField(max_length=50)
    country_code=models.CharField(max_length=50,null=True,blank=True)

# state lookup 
class State(models.Model):
    state_id=models.AutoField(auto_created=True,primary_key=True)
    state_name=models.CharField(max_length=50)
    country_id=models.ForeignKey(Country, on_delete=models.CASCADE,db_column='country_id')

甚至我第一次犯了同样的错误。

你可能正在尝试

State.country_id

并打印。 相反,你必须做

State.country_id.country_id

When you simply use the first option the output is the object State itself and not the country_id so you have to say the value of country_id inside the object country_id that's why you have to use a dot there.

因此,我们大多数人所做的就是在 class State内部,我们将字段名称称为国家而不是国家 ID,因为我们可以使用state “获取我的国家/地区”

State.country.country_id

暂无
暂无

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

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