总体而言,我对drf和django都很新鲜,但是我正在开发使用drf作为后端并以前端为响应的应用程序
当前,我正在为创建交易的模型序列化程序而苦苦挣扎,这将允许我对GET请求上的嵌套对象进行序列化(因为我需要引用的是例如要在表中显示的名称)并使用提供的外键创建事务(创建具有下拉菜单的vie表单),以作为相关子对象的参考。
我想知道什么是最好的方法,所以我考虑:
我已经在drf文档中和此处进行过一些研究,但是到目前为止,找不到满足我的需求或足够简单的解决方案。你能给我什么建议吗?
现在我遇到以下错误
{
"category": [
"This field is required."
],
"tag": [
"This field is required."
],
"transaction_type": [
"This field is required."
],
"payment_target": [
"This field is required."
],
"payment_source": [
"This field is required."
]
}
views.py
class BaseViewSet(viewsets.GenericViewSet,
mixins.ListModelMixin,
mixins.CreateModelMixin):
"""
A simple base viewset for creating and editing
"""
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
def get_queryset(self):
"""Return object for the current authenticated user only"""
assigned_only = bool(
int(self.request.query_params.get('assigned_only', 0))
)
queryset = self.queryset
if assigned_only:
queryset = queryset.filter(payment__isnull=False)
return queryset.filter(
user=self.request.user
class TransactionViewSet(BaseViewSet):
queryset = Transaction.objects.all()
serializer_class = TransactionSerializer
def get_queryset(self):
queryset = super().get_queryset()
query_params = self.request.query_params
query_data = QueryData(queryset, query_params)
filtered_data = query_data.queryset
return filtered_dat
serializers.py
class TransactionSerializer(serializers.ModelSerializer):
"""Serializer for Transaction object"""
category = CategorySerializer(many=False)
tag = TagSerializer(many=False)
transaction_type = TransactionTypeSerializer(many=False)
payment_target = PaymentSerializer(many=False)
payment_source = PaymentSerializer(many=False)
class Meta:
model = Transaction
fields = '__all__'
read_only_fields = ('id',)
models.py
class Transaction(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
transaction_date = models.DateField(
null=False,
blank=False)
category = models.ForeignKey(
Category,
on_delete=models.CASCADE)
tag = models.ForeignKey(
Tag,
on_delete=models.CASCADE,
null=True,
blank=True)
transaction_type = models.ForeignKey(
TransactionType,
on_delete=models.CASCADE)
payment_target = models.ForeignKey(
Payment,
related_name='payment_target',
on_delete=models.CASCADE,
blank=True,
null=True)
payment_source = models.ForeignKey(
Payment,
related_name='payment_source',
on_delete=models.CASCADE,
null=True,
blank=True)
description = models.CharField(
max_length=500,
blank=True)
amount = models.DecimalField(
max_digits=10,
decimal_places=2,
null=False,
blank=False)