嵌套序列化程序中的PUT / PATCH / DELETE方法覆盖

时间:2020-08-07 20:54:48

标签: django-rest-framework

模型定义如下:

class Company(models.Model):
    """Company related data"""
    name = models.CharField(max_length=120)
    abbrev = models.CharField(max_length=5)
    founded = models.IntegerField(null=False)
    country = models.CharField(max_length=60)


class StockQuote(models.Model):
    """Price history"""
    company = models.ForeignKey(Company, related_name='quotes', on_delete=models.CASCADE)
    fetch_date = models.DateField(default=timezone.now())
    business_day_date = models.DateField(default=timezone.now())
    price = models.CharField(max_length=8, default='0.00')

序列化器与嵌套一起玩。数据可以正确显示,并且create方法也可以正常工作,但是尝试使用以下update方法更新实例的结果是TypeError: update() takes 1 positional argument but 3 were given

class StockQuoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = StockQuote
        fields = ['fetch_date', 'business_day_date', 'price']


class CompanySerializer(serializers.ModelSerializer):
    quotes = StockQuoteSerializer(many=True)

    class Meta:
        model = Company
        fields = ['id', 'name', 'abbrev', 'founded', 'country']

    def create(self, validated_data):
        quotes_data = validated_data.pop('quotes')
        company = Company.objects.create(**validated_data)
        for quote_data in quotes_data:
            StockQuote.objects.create(company=company, **quote_data)
        company.save()
        return company

    def update(self, instance, validated_data):
        quotes_data = validated_data.pop('quotes')
        instance = super().update(instance, validated_data)
        for quote_data in quotes_data:
            StockQuote.objects.update(instance, validated_data)
        instance.save()
        return instance

问题:

  1. 上面的完整更新方法有什么问题?
  2. 应如何定义PATCH方法以将报价附加到嵌套报价列表中?
  3. 应如何实施DELETE方法以从嵌套报价列表中删除报价?

0 个答案:

没有答案