外键使用名称值在Django REST框架中获取

huangapple go评论64阅读模式
英文:

foregin key using name value fetch in django rest frame work

问题

我已添加了model.py、view.py和serializer.py文件,我将分享国家和州的模型。我将在国家和州字段上应用外键。我将在Django Rest Framework的HTML字段中仅获取对象ID而不是值,就像城市(Morbi)一样。

外键使用名称值在Django REST框架中获取

外键使用名称值在Django REST框架中获取

[外键使用名称值在Django REST框架中获取

英文:

i have add model.py ,view.py and serilializer.py file ,i will share country and state model .
I wiil apply foregin key country and state fields.
I will check in html fields in django rest framework in only object id fetch not value so like city(Morbi).

外键使用名称值在Django REST框架中获取

外键使用名称值在Django REST框架中获取

[外键使用名称值在Django REST框架中获取

答案1

得分: 0

Override the __str__() function in the model class to customize the dropdown correctly.

class Country(models.Model):
    # your data variables
    
    def __str__(self):
        return self.name # or any thing you want to show in dropdown

You can do the same with the state too.

英文:

Override the __str__() function in model class to customize the dropdown correctly.

class Country(models.Model):
    # your data variables
    
    def __str__(self):
        return self.name # or any thing you want to show in dropdown

same you can do with state too.

答案2

得分: 0

As Vinay has stated, add a return method to return some sort of detail to all your models. Also, make sure your model names start with a capital letter and there is no need to define the id as Django will always create that for you.

英文:

As Vinay has stated, add a return method to return some sort of detail to all your models. Also, make sure your model names start with a capital letter and there is no need to define the id as Django will always create that for you.

huangapple
  • 本文由 发表于 2023年6月15日 12:53:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定