1

I have two models Property and PropertyImage. Property holds all the data and PropertyImage is only for allowing an unlimited number of images to be uploaded.

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

What I want is to be able to add one field to the serialization of the Property class so that it will add the PropertyImage.url element. It does not need to be all of the url elements that the Property has, one would be enough. I am using this for previewing the Property.

Now, I have:

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

and of course the PropertyImage is left out and I can't find a clean way of adding it to the JSON and relating it with the Property it belongs.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Eliel Van Hojman
  • 433
  • 4
  • 13

1 Answers1

1

You can proceed with 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)

Here's an image_url field is set to the first() PropertyImage's url field value for the each Property instance in the results queryset.

Also see:

Hope that helps.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195