请原谅可能很明显是 python 新手。这是一个视图功能。它是一个 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 解码器中,例如http://json.parser.online.fr/中的那个
您会看到没有正确解析联系人元素。
我努力了:
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