AJAX的Django ORM问题

马林

我对函数ajax请求aobut Django ORM有疑问:

select_related

我有这样的查询:

prod_serv = Product_service.objects.select_related()

我在哪里加入models与外键有关的3 related_name在简单的Django for循环中,我可以像这样提取值:

{% 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 %}

最重要的部分是:

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

我可以在其中访问与值相关的名称。例子:

楷模

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)

siple for loop做得非常好,但是我想用ajax做到这一点。因此,当我将此查询发送到ajax时,我无法提取for循环中的值。

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')

我不知道我在这个查询中做错了什么,将其发送到ajax。还有其他方法可以使用从模型中提取的字段将值发送到ajax吗?

bwarren2

每当使用Django和Ajax时,都应该考虑一个rest框架(例如Django Rest Framework)。手动滚动自己的Ajax和端点正在重新发明轮子,而其他非常聪明的人已经为您开源了他们的代码。将框架与Ajax结合使用,可以使模型处理脱离Django请求-响应周期,并在浏览器中真正轻松地处理事情。

共有3个步骤:

  1. 安装DRF并设置一些模型端点
  2. 编写ajax请求以命中端点
  3. 根据响应处理DOM。

示例模板:

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 %}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章