Django ORM problems with AJAX
I have an aobut Django ORM question with ajax function request:
select_related
I have a request:
prod_serv = Product_service.objects.select_related()
Where I join 3 models
to foreign key c related_name
. In a simple Django loop, I can extract values like this:
{% for x in a %}
<td><label class="form-checkbox form-normal form-primary "><input type="checkbox" checked=""></label></td>
<td class="hidden-xs">{{ x.product_code }}</td>
<td class="hidden-xs">{{ x.name }}</td>
<td class="hidden-xs">{{ x.description }}</td>
<td class="hidden-xs">{{ x.selling_price }}</td>
<td class="hidden-xs">{{ x.unit_id }}</td>
<td class="hidden-xs">{{ x.category_id.type_id }}</td>
{% endfor %}
The most important part:
- x.category_id.type_id
- x.unit_id
Where can I access the values associated with the name. Example:
Models
class Product_service(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
selling_price = models.DecimalField(decimal_places=5, max_digits=255, blank=True, null=True)
purchase_price = models.DecimalField(decimal_places=5, max_digits=255, blank=True, null=True)
description = models.CharField(max_length=255, blank=True, null=True)
image = models.FileField(upload_to="/", blank=True, null=True)
product_code = models.CharField(max_length=255, blank=True, null=True)
product_code_supplier = models.CharField(max_length=255, blank=True, null=True)
product_code_buyer = models.CharField(max_length=255, blank=True, null=True)
min_unit_state = models.CharField(max_length=255, blank=True, null=True)
state = models.CharField(max_length=255, blank=True, null=True)
vat_id = models.ForeignKey('VatRate', related_name='vat_rate')
unit_id = models.ForeignKey('Units', related_name='unit_value')
category_id = models.ForeignKey('Category', related_name='product_services')
def __str__(self):
return self.name
class Units(models.Model):
id = models.AutoField(primary_key=True)
unit_name = models.CharField(max_length=255)
def __str__(self):
return self.unit_name
class VatRate(models.Model):
id = models.AutoField(primary_key=True)
rate = models.CharField(max_length=255)
description = models.CharField(max_length=255)
def __str__(self):
return self.rate
class CategoryType(models.Model):
id = models.AutoField(primary_key=True)
type = models.CharField(max_length=255)
def __str__(self):
return self.type
class Category(models.Model):
id = models.AutoField(primary_key=True)
type_id = models.ForeignKey('CategoryType')
name = models.CharField(max_length=255)
def __str__(self):
return str(self.name)
The for-loop does everything right, but I want to do it with ajax. So when I post this request in ajax, I cannot retrieve values like in for loop.
views.py
@login_required
@csrf_protect
def ajax_request(request):
prod_serv = Product_service.objects.select_related()
if request.is_ajax():
mega = serializers.serialize('json', prod_serv)
return HttpResponse(mega, 'json')
I dont know what I am doing wrong in this request by sending it in ajax. Is there any other way to send values to ajax with extracted fields from models?
source to share
Whenever you use Django and Ajax, you should think about a rest framework (like Django Rest Framework ). Hand rewinding your own ajax and endpoints is like reinventing the wheel while other very smart people open up their code for you. Using a framework with Ajax allows you to break your model manipulation out of the Django request-response loop and handle things easily in the browser.
There are three steps:
- Install DRF and adjust model endpoints
- Write ajax request to reach the endpoint.
- Manipulate the DOM based on the response.
Example template:
template.html
{% block extra_js %}
<script type="text/javascript">
// Forgive the pseudocode, I have not run this.
// Uses jquery because everything does.
// For each item in an array, add it to a selected table in a new row
var do_dom_manipulation = function(data){
$.each(data, function(d){
$('table.mytable').append('<tr>'+d+'<tr>')
})
}
// Hit the rest endpoint to get data from the browser
$.ajax('api/models',
{
'name': 'foo'
}
).done(function(data) {
alert( "success" );
do_dom_manipulation(data)
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
</script>
{% endblock extra_js %}
source to share