Django没有序列化自然键值

时间:2014-04-25 16:17:32

标签: python django

我有一个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()

但是我的序列化程序仍然没有输出外键的元素

[
{
  "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
  }
}
]

我哪里错了?

1 个答案:

答案 0 :(得分:2)

您需要在def natural_key(self)模型中添加AcademicPrograms方法。序列化时,您还必须传递use_natural_foreign_keys=Trueuse_natural_primary_keys=True。有关示例,请参阅django docs