Django延迟加载引用对象的数据

时间:2014-01-14 05:33:01

标签: django foreign-keys lazy-loading

我是Django& amp;的全新手。蟒!

我在models.py

中有以下课程
class MyUser(models.Model):
    useruniqueid = models.AutoField(primary_key=True) #BigIntegerField(primary_key=True)
    name = models.CharField(max_length=50)
    nickname = models.CharField(max_length=50)
    phonenumber = models.CharField(max_length=20, unique=True)
    class Meta:
        managed = True
        db_table = 'myuser'

和另一个参考MyUser的课程

class MyCompany(models.Model):
    uniqueid = models.AutoField(primary_key=True) #BigIntegerField(primary_key=True)
    user = models.ForeignKey(MyUser, db_column='useruniqueid')
    name = models.CharField(max_length=50)
    country = models.CharField(max_length=100)
    city = models.CharField(max_length=100)
    class Meta:
        managed = True
        db_table = 'mycompany'

在我的views.py中执行如下查询:

def companyDetails(request, id):
    property = MyCompany.objects.filter(uniqueid=id)
    output = serializers.serialize('json',property, fields=('uniqueid','name','country','city')
    return HttpResponse(output, content_type="application/json")

我还要序列化用户字段,如手机和昵称,我该怎么做,我读了教程以及https://docs.djangoproject.com/en/1.6/ref/models/relations/,但我可以解决这个问题。

1 个答案:

答案 0 :(得分:0)

Django序列化程序扩展外键并不灵活。此外,一旦序列化查询集,它就不再是延迟加载的。所以我认为最灵活的选择是自己构建JSON文档。例如:

import json

def companyDetails(request, id):
    json_doc = []
    for c in MyCompany.objects.filter(uniqueid=id):
        jobj = {}
        jobj['uniqueid'] = c.uniqueid
        jobj['name'] = c.name
        jobj['country'] = c.country
        jobj['city'] = c.city
        jobj['user'] = {"name": c.user.name, 
                        "nickname": c.user.nickname, 
                        "phonenumber": c.user.phonenumber}
        json_doc.append(jobj)
    return HttpResponse(json.dumps(json_doc, indent=2), content_type="application/json")