我有两个模型PropertyPropertyImage
Property保存所有数据,PropertyImage仅用于允许无限数量的图像上载。

 class PropertyImage(models.Model):
     property = models.ForeignKey(Property, related_name='images')
     url = models.ImageField(upload_to=property_image_name)


我想要的是能够向Property类的序列化添加一个字段,以便它将添加PropertyImage.url元素。它不必是url拥有的所有Property元素,一个就足够了。我正在用它来预览属性。

我现在有:

results = Property.objects.raw(mysql_query)
markers = serializers.serialize('json',results)


当然PropertyImage被遗漏了,我找不到将其添加到JSON并将其与它所属的Property关联的干净方法。

最佳答案

您可以继续model_to_dict()

import json
from django.forms.models import model_to_dict

results = Property.objects.raw(mysql_query)
data = []
for result in results:
    model = model_to_dict(result)
    model['image_url'] = model.property_image_set.first().url
    data.append(model)

markers = json.dumps(data)


对于image_url查询集中的每个first()实例,这是一个PropertyImage字段设置为url Propertyresults字段值。

另请参阅:


Django reverse lookup of foreign keys
How to JSON serialize __dict__ of a Django model?


希望能有所帮助。

10-04 10:49