Django ListCreateAPIView帖子,带有带注释的字段,该字段为';序列化程序中的s不是模型
我正在构建一个简单的预算应用程序来学习Django&React。我使用DRF构建了一个API,用于从数据库中创建和获取事务。我目前正在计算总运行平衡的飞行时,我做我的得到。这一直工作得很好,但是当我发布一篇文章时,我得到一个错误,我的动态平衡字段是必需的,因为该字段在我的序列化程序中。我怎样才能避开这件事 views.pyDjango ListCreateAPIView帖子,带有带注释的字段,该字段为';序列化程序中的s不是模型,django,django-rest-framework,Django,Django Rest Framework,我正在构建一个简单的预算应用程序来学习Django&React。我使用DRF构建了一个API,用于从数据库中创建和获取事务。我目前正在计算总运行平衡的飞行时,我做我的得到。这一直工作得很好,但是当我发布一篇文章时,我得到一个错误,我的动态平衡字段是必需的,因为该字段在我的序列化程序中。我怎样才能避开这件事 views.py class CreateView(generics.ListCreateAPIView): """This class defines the GET & P
class CreateView(generics.ListCreateAPIView):
"""This class defines the GET & POST behavior of the rest api."""
queryset = Transaction.objects.all()
# This is the balance that's calculated on the fly
queryset_with_balance = queryset.annotate(balance=Window(Sum('amount'),
order_by=F('created_time').asc())).all().order_by('-created_time')
serializer_class = TransactionSerializer
def perform_create(self, serializer):
"""Save the post data when creating a new transaction."""
serializer.save()
def get_queryset(self):
return self.queryset_with_balance
序列化程序.py
class TransactionSerializer(serializers.ModelSerializer):
balance = serializers.DecimalField(decimal_places=2, max_digits=19)
class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Transaction
fields = ('id', 'date', 'payee', 'category',
'amount', 'balance', 'created_time', 'modified_time')
models.py
class Transaction(models.Model):
date = models.DateField()
payee = models.CharField(max_length=256)
category = models.CharField(max_length=256)
amount = MoneyField(max_digits=19,
decimal_places=2,
default_currency='USD')
created_time = models.DateTimeField(auto_now_add=True)
modified_time = models.DateTimeField(auto_now=True)
将
余额
字段设置为只读
如下,class TransactionSerializer(serializers.ModelSerializer):
balance = serializers.DecimalField(decimal_places=2, max_digits=19, read_only=True)
# your code
class TransactionSerializer(serializers.ModelSerializer):
balance=序列化程序。小数字段(小数位数=2,最大位数=19,只读=True)
#您的代码
从
只读字段包含在API输出中,但在创建或更新操作期间不应包含在输入中
当
HTTP POST
时,您是否需要此balance
字段?您可以将queryset\u与\u balance一起移动,或仅将注释移动到def get\u queryset(self):
仅在get上需要balance。我没有将其存储在数据库中。@brewcrazy在下面检查我的答案:)希望这能解决问题:)