Django,过滤对象并返回对象和对象父对象

时间:2014-05-02 16:34:35

标签: python django

我有两个模特**

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

2 个答案:

答案 0 :(得分:1)

您可以使用Django' built-in serializersnatural 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