使用嵌套对象QuerySet到JSON

时间:2017-02-12 02:49:08

标签: python json django django-queryset

我有2个班级EligibilityCriteria,奖学金。奖学金将EligibilityCriteria作为外键引用。

class EligibilityCriteria(models.Model):
    criteria_id = models.AutoField(primary_key=True)
    gender = models.ForeignKey(Gender, null=True, blank=True)
    minimum_age = models.IntegerField(blank=True, null=True)
    maximum_age = models.IntegerField(blank=True, null=True)
    eligibility_colleges = models.TextField(blank=True, null=True)
    state = models.ForeignKey(State, blank=True, null=True, on_delete=SET_NULL)
    caste = models.ForeignKey(Caste, blank=True, null=True, on_delete=SET_NULL)
    religion = models.ForeignKey(Religion, blank=True, null=True, on_delete=SET_NULL)
    education_level = models.ForeignKey(Education_level, blank=True, null=True, on_delete=SET_NULL)
    minimum_percentage = models.CharField(max_length=100, blank=True, null=True)
    income_ceiling = models.IntegerField(blank=True, null=True)
    other_criteria = models.TextField(blank=True, null=True)

    def __unicode__(self):
        return str(self.education_level) + "_" + str(self.state) + "_" + str(self.gender)

class Scholarship(models.Model):
    scholarship_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=500)
    description = models.TextField()
    eligibility_criteria = models.ForeignKey(EligibilityCriteria, null=True, on_delete=models.CASCADE)
    scholarship_category = models.ForeignKey(ApplicantCategory, blank=False, null=False, on_delete=CASCADE)
    end_date = models.DateTimeField(null=True, blank=True)
    availability_count = models.IntegerField(null=True, blank=True)
    website_link = models.CharField(max_length=500, blank=True, null=True)
    amount = models.CharField(max_length=100, blank=True, null=True)
    selection_procedure = models.TextField(blank=True, null=True)

    def __unicode__(self):
        return str(self.name)

现在,当我将奖学金的QuerySet转换为json时,缺少EligibilityCriteria的值:

def get_all_scholarships(request):
    scholarships_list = Scholarship.objects.all()
    # return JsonResponse(scholarships_list, safe=False)
    response_obj = serializers.serialize('json', scholarships_list,
                                 fields=('name','description', 'eligibility_criteria', 'scholarship_category', 'end_date',
                                         'availability_count', 'website_link', 'amount', 'selection_procedure'))

    return django.http.HttpResponse(__set.encode('utf-8'), content_type='application/json')

结果:

[{"model": "scholarship.scholarship", "pk": 1, "fields": {"name": "BlynQ Creative Scholarship", "description": "Most creative UI Designer", "eligibility_criteria": 2, "scholarship_category": 5, "end_date": "2017-02-20T00:00:00Z", "availability_count": null, "website_link": "www.blynq.in", "amount": "20000", "selection_procedure": "From open source repositories"}]

如何将奖学金对象的QuerySet转换为json,使得资格标准内的值均匀可见?

0 个答案:

没有答案