我有两个模特**
class Person(models.Model):
first_name = models.CharField(max_length=45)
last_name = models.CharField(max_length=45)
doc = models.CharField(max_length=45, db_index=True)
class Salary(models.Model):
year = models.IntegerField(max_length=4)
salary = models.IntegerField()
person = models.ForeignKey(Person)
在我看来,我需要过滤Salary并返回Salary和Person来返回json
class SearchPersonSalary(TemplateView):
def get(self, request, *args, **kwargs):
doc = request.GET['doc']
salary = Salary.objects.filter(person__doc=doc)
data = serializers.serialize('json', salary)
return HttpResponse(data, mimetype='application/json')
返回json>>
" [{" pk":1," model":" salary"," fields":{&# 34;年":2014年,"薪水":10121,"人":1}}]
我也需要人的详细信息,例如
[{" pk":1," model":" salary"," fields":{" year&# 34;:2014年,"薪水":10121,"人":{" fisrt_name":" jhon"," last_name&# 34;:" huld"," doc":2343432}}}]"
答案 0 :(得分:1)
您可以使用Django' built-in serializers和natural key serialization feature:
在相关模型上定义natural_key()
方法:
class Person(models.Model):
first_name = models.CharField(max_length=45)
last_name = models.CharField(max_length=45)
doc = models.CharField(max_length=45, db_index=True)
def natural_key(self):
return (self.first_name, self.last_name, self.doc)
将django.core.serializers.serialize()
与use_natural_keys=True
参数一起使用:
from django.core.serializers import serialize
serialize('json', Salary.objects.filter(person__doc=doc), use_natural_keys=True)
现在,您的序列化数据不仅包含Person
的外键,而且还包含Person
方法返回的natural_key()
个模型字段。
希望有所帮助。
答案 1 :(得分:0)
django-rest-framework有一个json序列化器。看看here。