[英]Django not serializing the natural key values
I have a django model where i use natural keys: 我有一个使用自然键的Django模型:
class AcademicProgramsManager(models.Manager):
def get_by_natural_key(self, acad_program_id, program_title, required_credits):
return self.get(acad_program_id = acad_program_id, program_title = program_title, required_credits = required_credits)
class AcademicPrograms(models.Model):
objects = AcademicProgramsManager()
acad_program_id = models.IntegerField(primary_key=True)
acad_program_category = models.ForeignKey(AcademicProgramCategories)
acad_program_type = models.ForeignKey(AcademicProgramTypes)
acad_program_code = models.CharField(max_length=25)
program_title = models.CharField(max_length=64)
required_credits = models.IntegerField()
min_gpa = models.FloatField()
description = models.CharField(max_length=1000)
class StudentAcademicPrograms(models.Model):
student = models.ForeignKey(Students)
academic_program = models.ForeignKey(AcademicPrograms)
credits_completed = models.IntegerField()
academic_program_gpa = models.FloatField()
primary_program = models.BooleanField()
But my serializer still does not output the elements of the foreign key 但是我的序列化器仍然不输出外键的元素
[
{
"pk": 1,
"model": "studentapp.studentacademicprograms",
"fields": {
"academic_program": 124,
"credits_completed": 32,
"primary_program": true,
"student": 1206,
"academic_program_gpa": 3.7
}
},
{
"pk": 2,
"model": "studentapp.studentacademicprograms",
"fields": {
"academic_program": 123,
"credits_completed": 32,
"primary_program": false,
"student": 1206,
"academic_program_gpa": 3.4
}
}
]
Where am i going wrong? 我要去哪里错了?
You need to add a def natural_key(self)
method to your AcademicPrograms
model. 您需要在自己的AcademicPrograms
模型中添加一个def natural_key(self)
方法。 You must also pass use_natural_foreign_keys=True
or use_natural_primary_keys=True
when serializing. 序列化时,还必须传递use_natural_foreign_keys=True
或use_natural_primary_keys=True
。 See the django docs for an example. 有关示例,请参见django文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.