Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM problems with AJAX

I have question aobut Django ORM with ajax request on function:

select_related

I have query like this:

prod_serv = Product_service.objects.select_related()

Where I join 3 models on foreign key with related_name. In simple Django for 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 importan part is :

  1. x.category_id.type_id
  2. x.unit_id

Where I can access values related 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 siple for loop doing everthin right, but I wanna do this with ajax. So when i send this query to ajax i cant extract 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 Im I doing wrong in this query sending it to ajax. Is there some other way to send values to ajax with extracted fields from models?

like image 486
Marin Avatar asked Jun 18 '26 19:06

Marin


1 Answers

Whenever you are using Django and Ajax, you should be thinking of a rest framework (like Django Rest Framework). Hand-rolling your own ajax & endpoints is reinventing the wheel, while other very smart people have open sourced their code for you. Using a framework with Ajax lets you break your model manipulation out of the Django request-response cycle and handle things really easily in the browser.

There are 3 steps:

  1. Install DRF and set up some model endpoints
  2. Write the ajax request to hit your endpoint
  3. 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 %}
like image 86
bwarren2 Avatar answered Jun 21 '26 08:06

bwarren2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!