我有两个模型Property
和PropertyImage
。
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
Property
的results
字段值。另请参阅:
Django reverse lookup of foreign keys
How to JSON serialize __dict__ of a Django model?
希望能有所帮助。