【问题标题】:Over-riding update method in django modelViewSet在 Django modelViewSet 中覆盖更新方法
【发布时间】:2015-12-25 18:04:35
【问题描述】:

我在 django 的序列化程序类上定义更新方法时遇到问题。这是我的基本模型

class Category(models.Model):
    category = models.CharField(max_length = 100)

    def __str__(self):
        return self.category

class Items(models.Model):
    category = models.ForeignKey(Category)
    item = models.CharField(max_length = 100)
    rate = models.DecimalField(max_digits = 20,decimal_places =2)

    def __str__(self):
        return self.item

下面是我的序列化器:

class ItemSerializer(serializers.ModelSerializer):
    category = serializers.CharField(source = 'category.category',read_only = True)
    category_pk = serializers.IntegerField(source = 'category.pk')

    class Meta:
        model = Items
        fields = ('pk','category','category_pk','item','rate',)

    def update(self,instance,validated_data):

        category_pk = validated_data.get('category_pk',instance.category_pk)
        instance.category = Category.objects.get(pk = category_pk)
        instance.item = validated_data.get('item',instance.item)
        instance.rate = validated_data.get('rate',instance.rate)

        instance.save()
        return instance

使用 AJAX 中的 PUT 方法时出现错误,指出 Item 对象没有 category_pk 字段(但我没有在 instance.save() 方法中包含该字段)

下面是我的 AJAX 请求

$('#update-item').on('click',function(){

    var dat = {
      'category':$("#category-box").find('option[value='+cat_pk+']').text(),
      'category_pk':$('#category-box').val(),
      'item':$('#Items').val(),
      'rate':$('#Rate').val()
      };
      console.log(dat);

    $.ajax({
      type : 'PUT',
      url: 'http://127.0.0.1:8000/billing/items/'+pk+'/',
      data : JSON.stringify(dat),
      contentType: 'application/json',
      crossDomain:true,
      success : function(json){
        alert('ok');

      },
      error : function(json){
        alert('error with PUT')
      }
    });
  });

我重写了 update 方法,因为 rest 框架最初抛出了一个错误,指出它不能写入嵌套字段。

KJ

【问题讨论】:

  • 您是否检查并确认$('#category-box').val() 包含数据?它包含什么?我不知道您在cat_pk 中持有什么,或者它与category_pk 之间的区别是什么,但错误使问题似乎是您没有将正确的数据传递给@ 987654327@前端。

标签: python ajax django django-rest-framework


【解决方案1】:

默认情况下,DRF 将 pk 用于 ModelSerializer 上的类别字段,但在您的情况下,您将类别字段设置为 read_only=True,并且您的模型上没有 category_pk 字段。我会像这样更改序列化程序,然后将 pk 发布到类别字段而不是 category_pk 字段。然后,您还可以删除更新方法覆盖。

class ItemSerializer(serializers.ModelSerializer):
    # I assume you changed the category field to readonly to display the text of the category
    category_name = serializers.ReadOnlyField(source='category.category')

    class Meta:
        model = Items
        fields = ('pk','category','category_name','item','rate',)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2019-05-04
    • 2018-02-05
    • 2011-01-19
    • 2014-01-04
    • 2018-10-12
    • 2017-12-11
    相关资源
    最近更新 更多