[英]serializing two different models with django
我有兩個模型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
元素。 它不一定是Property
擁有的所有url
元素,一個就足夠了。 我正在用它來預覽屬性。
我現在有:
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
字段,它設置為results
queryset中每個Property
實例的first()
PropertyImage
的url
字段值。
另請參閱:
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.