1

i'm trying to fetch data from jsonResponse into ajax , but in the foreign key field it returns object_id instead of the object name

my models.py

class Product(models.Model):
    item = models.CharField(max_length=50)

class Item(models.Model):
    item = models.ForeignKey(Product,on_delete=models.CASCADE)
    active = models.BooleanField(active=True)

my views.py

def alerts(request):
    if request.is_ajax:
        data = Item.objects.filter(active=False).values()
        print(data)
        return JsonResponse({'items':list(data)})

#print(data) returns this

<QuerySet [{'id': 13, 'item_id': 14, 'active': False}]>

i dont know how to return item name instead its id (item_id)

  $(document).ready(function(){
      $('.btn-click').click(function(){
          $.ajax({
              url:'{% url 'maininfo:alerts' %}',
              dataType:'json',
              type:'GET',
              success:function(data){
                var obj = data.items
                var mainObj = data.items;
                var k = '<tbody>'
                for(i = 0;i < data.items.length; i++){
                  k+= '<tr>';
                  k+= '<td>' + mainObj[i]["item_id"] + '</td>';
 '</td>';

                  k+= '</tr>';                  
                }
                k+='</tbody>';
                document.getElementById('tableData').innerHTML = k;
              }

          })
      })
  })
        <div x-data="{ dropdownOpen: false }">
          <button @click="dropdownOpen = !dropdownOpen"
            class="relative z-10 block rounded-md text-black p-2 focus:outline-none btn-click">
            <i class="fas fa-bell"></i>
          </button>
      
          <div x-show="dropdownOpen"
            class="absolute left-2 top-10 text-right py-2 w-59 grayBG rounded-md shadow-xl z-20 h-48 overflow-y-scroll ">
            <table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
              <thead>
                  <tr>
                      <th width="30%">deactive items</th>
                  </tr>
              </thead>
                  <tbody id="tableData"></tbody>
              </table>

      
          </div>
        </div>

is there something wrong within my json response ? or a better approach to achieve it

1 Answer 1

1

You can add these to the .values(…) [Django-doc], thus:

from django.db.models import F

def alerts(request):
    if request.is_ajax:
        data = Item.objects.filter(active=False).values(
            'id',
            name=F('item__item')
        )
        print(data)
        return JsonResponse({'items':list(data)})

But using .values(…) is often not a good idea, even for JSOn serialization. You can use Django's serialization framework or work with the Django REST framework (DRF). DRF has better tooling to serialize, and make CRUD views.

Sign up to request clarification or add additional context in comments.

1 Comment

i can thank you enough , i appreciate your answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.