模型定义如下:
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
问题:
PATCH
方法以将报价附加到嵌套报价列表中?DELETE
方法以从嵌套报价列表中删除报价?