Python 用另一个对象(来自不同的queryset)覆盖对象元素(来自queryset)以进行json编码

Python 用另一个对象(来自不同的queryset)覆盖对象元素(来自queryset)以进行json编码,python,django,Python,Django,请原谅可能变得明显的python noobness。这里有一个视图函数。这是一个jsonp响应,并且完全按照要求工作,非常出色(一些元素经过了修改以获得更大的灵活性) 更新:这是我的功能,已完成。 class stores(ListView): model = Store def get_queryset(self): args = [Q()] output = [] callback = self.request.GET.g

请原谅可能变得明显的python noobness。这里有一个视图函数。这是一个jsonp响应,并且完全按照要求工作,非常出色(一些元素经过了修改以获得更大的灵活性)

更新:这是我的功能,已完成。

class stores(ListView):
    model = Store

    def get_queryset(self):

        args = [Q()]
        output = []

        callback = self.request.GET.get('callback', False)
        region = self.request.GET.get('region', False)
        country = self.request.GET.get('country', False)

        if region:
            args.append(Q(country__region_id=int(region)))

        if country:
            args.append(Q(country=int(country)))

        outputs =  self.model.objects.filter(reduce(operator.and_, args))

        for i, item in enumerate(outputs):
            outputs[i].contacts = pk__in=list(list(Contact.objects.filter(store=item.id).values()))

        return '%s(%s)' % (callback, json) if callback != False else json
这是我从脚本中得到的响应

[{"pk": 2837, "model": "store.store", "fields": {"geolocation": "-30.8040344,111.8395886", "code": "", "logo": "dist/logo/theshop_Sykes_9.jpg", "photo": "", "postcode": "2222/1111", "openinghours": "", "exclude": false, "city": "Perth", "dealer_type": "distrib", "contacts": "[{'phone': u' +1111 7000', 'fax': u'+61 2222 2122', 'type': u'general', 'email': u'notworking@theshop.com'}, {'phone': u'+61 2222 1111', 'fax': u'+61 1111 2222', 'type': u'general', 'email': u'notworking@theshop.com'}]", "servedcountries": [{"lat": "-25.244398", "lng": "132.775136", "name": "Oz"}], "comments": "", "state": "", "latitude": "-31.8040344", "legal_store": "theshop Pty Ltd", "updated": "2013-08-06T15:11:15Z", "street1": "thehouse", "street2": "Landsdale", "street3": "", "phone": "", "address": "The house", "product_type": [], "name": "theshop Pty Ltd", "sectors": "Industrial", "created": "2013-08-06T13:50:48Z", "url": "http://www.theshopsykes.com/", "country": {"lat": "-25.274398", "lng": "133.775136", "name": "Australia"}, "longitude": "115.8395886", "local_store": "theshop Pty Ltd"}}]
将该字符串粘贴到json解码器中,就像在

您将看到contacts元素没有正确解析

我试过:

outputs[i].contacts = serializers.serialize("json", Contact.objects.filter(distributor=item.id), use_natural_keys=True)
但是我犯了一个错误

AttributeError: 'unicode' object has no attribute 'name'
这是模型声明,以防有所帮助

class Contact(models.Model):
    contact_type = models.CharField('Email Type', max_length='20', choices=(('sales', 'Sales'), ('support', 'Support'), ('general', 'General')), blank=True)
    email = models.EmailField(max_length=200, blank=True)
    phone = models.CharField('Phone Number', max_length=200, blank=True)
    fax = models.CharField('Fax Number', max_length=200, blank=True)
    store = models.ForeignKey(Store)

    def __unicode__(self):
        return self.contact_type

    def natural_key(self):
        return self.contact_type

我猜您正在寻找序列化相关对象(联系人,与存储相关)

由于这是一个非常重要的问题,我建议大家看看类似这样的东西——不确定Django core中是否也有更新的选项(与select_相关?)


干杯,

史蒂夫,我认为你对序列化工作原理的思考是有缺陷的。我将从queryset到JSON响应的过程设想为两步过程,Django序列化程序同时完成这两个过程

1) 将查询集转换为字符串和数字字典。 2) 将该字典转换为JSON

第一步比想象的要难。例如,序列化程序必须决定序列化哪些属性。例如,如果您在模型上定义了一个属性,则它们似乎正在被序列化(否则联系人将不会显示)。我原以为Django序列化程序只序列化模型字段,但我猜不是

它还必须决定如何表示与其他模型的关系。这称为嵌套,有多个选项:只需列出相关模型的主键,或包含其序列化版本。可以只列出相关模型的主键,也可以包含一个或多个深度级别

--

就解决您的问题而言,我可以建议两件事:

  • 正如madflo所建议的,Django序列化程序对于您的需求来说可能太基本了。我想看看还有什么可用的。就个人而言,我是Django Rest框架的忠实粉丝;但对于您的用例来说,这可能是过分的。他们关于嵌套的文档可能仍然有用
  • 我想好好看看
    服务国家
    联系人
    之间的区别。看来,
    servedcountries
    是一个相关的模型,它正在按预期进行序列化,所以请找出原因,
    contacts
    并非如此。包含存储模型的声明会很有帮助
备注:

我不太确定这一行;我想你的意思是列表中的pk

outputs[i].contacts = pk__in=list(list(Contact.objects.filter(store=item.id).values()))
无论如何,如果我理解正确的话,你可以用

outputs[i].contacts = Contacts.objects.filter(store=item.id).values_list('pk', flat=True)

不确定我是否遵循您期望的输出类型。是否要在与您的请求匹配的每个门店上添加.contact属性?是。我希望每个商店都有一个联系人属性,包含每个商店的所有联系人。这基本上已经发生了,只是数据在json编码之前显然已经序列化了,这意味着contacts属性不能被接收脚本(在本例中是angularjs项目)使用。我实际上认为contacts已经被序列化了。我希望它们与执行json编码的其余数据一起序列化。我想我想要的是把查询集转换成字典。queryset是对象的集合。因此,您希望能够将对象转换为字典。这意味着你想将它们序列化:-)与你的兴趣相关:我真的非常感谢你的帮助。然而,我仍然完全困惑不解。我希望我不是,相信我-我正在尝试概念化这一点,所以我自己解决它。我尝试了一些对我有意义的事情,但是遇到了各种各样的问题。。。“outputs[i].contacts=serializers.serialize(“json”,Contact.objects.filter(store=item.id),use\u natural\u keys=True)”会导致“AttributeError:'unicode'对象没有属性‘name’”。其他尝试也有类似的结果。