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
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',
)
print(data)
return JsonResponse({'items':list(data)})
But using .values(…)
is often not a good idea, even for JSOn serialization. You can useDjango's serialization framework or work with the Django REST framework (DRF) . DRF has better tooling to serialize, and make CRUD views.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.