-1
---models.py---

class Products(models.Model):
    category = models.ForeignKey(Category)
    name= models.CharField(max_length=120, unique=True)
    slug = models.SlugField(unique = True)
    price = models.IntegerField(default=100)

class Image(models.Model):
    property = models.ForeignKey(Products, related_name='images')
    image = models.ImageField(upload_to='static/images/home',blank=True,null=True)

---views.py----

if request.is_ajax():
    query = Products.objects.all()
    p = Paginator(query, 4)
    pagedata = p.page(1)
    jsondata = serializers.serialize('json', pagedata.object_list)
    data = json.dumps({'id' : jsondata,})
    return HttpResponse(data, content_type='application/json')

now in ajax data are in (pk, category, name, slug ,price)

but i also want foreign key field i.e 'image' using reverse lookup in ajax. i have already tried list but i want to do using reverse lookup..

Harish
  • 425
  • 7
  • 22
  • i have tried list but this is not good method. so i am looking for reverse lookup. in my question i want to know that jsondata = serializers.serialize('json', pagedata.object_list.?????????) so what to write here so that i will get the fields of foreign table as well – Harish Oct 30 '15 at 19:07

1 Answers1

1

You cannot use serializers.serialize and then json.dumps on your stuff. serializers.serialize is basically doing the same thing as json.dumps, to convert a python object into json string. What you need to do is manually construct a dictionary that contains all your data. You might need to loop through the Product list because there's no way to query for reverse relationships for each item in one run.

Shang Wang
  • 24,909
  • 20
  • 73
  • 94