簡體   English   中英

用Django序列化兩個不同的模型

[英]serializing two different models with django

我有兩個模型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元素。 它不一定是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() PropertyImageurl字段值。

另請參閱:

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM