Harish
Harish

Reputation: 425

how to get foreign key fields using reverse lookup in python/django ajax request (json)

---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..

Upvotes: -1

Views: 654

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

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.

Upvotes: 1

Related Questions