0

I need to get data in template.

I have ajax request:

$(".retailer-list-img").mouseover(function () {
    var $this = $(this);
    var category_id = $this.attr('id');
    $.ajax({
        'url': '/shop/getfeatured/',
        'method': 'POST',
        'data': {'category_id': category_id,},
        'success': function(response){
             console.log(response)
         }
    });
});

views.py

def MerchantGetfeaturedView(request):
    featured = Merchant.objects.filter(
        is_catalog_active=1,
        is_active=1,
        category_id=request.REQUEST.get('category_id'),
        date_deleted__isnull=True
    ).select_related('_image')

    featured = serializers.serialize('json', featured)

    return HttpResponse(featured, content_type="application/json")

But there is no related object "image"? How to serialize related model? Thanks.

Alex Pavlov
  • 571
  • 1
  • 7
  • 24
  • your question isn't very clear. Can you post a traceback of your error? – Moses Koledoye May 19 '16 at 13:00
  • please update the question to add models – Muhammad Shoaib May 19 '16 at 13:05
  • I would personally avoid using the serializers for an AJAX request as it exposes information about your database structure that end-users don't need to know. You can use something like `featured = json.dumps(list(featured.values('name','category_id','...')))`. Also, you may need to remove the underscore in `select_related("_image")` – raphv May 19 '16 at 13:08
  • Similar question: https://stackoverflow.com/questions/3753359/serializing-foreign-key-objects-in-django – AndreyT May 19 '16 at 13:11

1 Answers1

0

First, you have to transform your object.

result = { 'is_catalog_active': featured['is_catalog_active']
           'is_active': 1,
           'category_id': int(request.REQUEST.get('category_id')),
           'image_id' : _image.id,
           'image_name': _image.name 
         }

You can have PyCharm to help you auto-complete related model field. Random guessing sometimes is bad, if you have right tool. Alternatively, check django document for further investigation.

Secondly, $.ajax() function don't have fail callback, so the pattern is not complete. In reality, user have to know front end feed back. e.g. which type of error.

CodeFarmer
  • 2,644
  • 1
  • 23
  • 32