我正在撰写一个小型系统,其Account
与Category
和PrimaryKeyRelatedField
相关。目前我在TransactionSerializer
中使用GET
。我需要在Account
所有事务或仅一个事务时返回JSON响应中的相关Category
和PrimaryKeyRelatedField
详细信息。通过使用class TransactionSerializer(serializers.ModelSerializer):
account = serializers.PrimaryKeyRelatedField(read_only=True)
category = serializers.PrimaryKeyRelatedField(read_only=True)
# output:
[
transaction: {
id: 1,
account: 1
category: 3,
...
},
...
]
,响应类似于:
TransactionSerializer
为了详细说明相关帐户和类别,我在class TransactionSerializer(serializers.ModelSerializer):
account = AccountSerializer()
category = CategorySerializer()
# output:
[
transaction: {
id: 1,
account: { id: 1, name: "Foo", ... }
category: { id: 3, name: "Bar", ... },
...
},
...
]
中完成了以下操作:
account
但后来我无法创建新的交易。它显示错误,指出category
和read_only
是必需的。我已经尝试将字段移动到序列化程序中的fields
,但是另一个错误说这些字段应该在views.py
列表中。
完整class TransactionList(APIView):
def get(self, request):
user_id = request.user.pk
transactions = Transaction.objects.filter(user_id=user_id).order_by('-created_at')
serializer = TransactionSerializer(transactions, many=True)
return Response(serializer.data)
def post(self, request):
account = Account.objects.get(pk=request.data['account'])
category = Category.objects.get(pk=request.data['category'])
serializer = TransactionSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=request.user, account=account, category=category)
return Response(serializer.data, status=HTTP_201_CREATED)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
class TransactionDetail(APIView):
def get(self, request, pk):
try:
transaction = Transaction.objects.get(pk=pk)
serializer = TransactionSerializer(transaction)
return Response(serializer.data)
except:
raise Http404
次交易:
urls.py
urlpatterns = [
url(r'^$', views.TransactionList.as_view(), name="transaction_list"),
url(r'^(?P<pk>[0-9]+)/$', views.TransactionDetail.as_view(), name="transaction"),
]
:
models.py
class Transaction(models.Model):
user = models.ForeignKey(User, default=None)
account = models.ForeignKey(Account, default=None)
category = models.ForeignKey(Category, default=None)
name = models.CharField(max_length=32)
amount = models.DecimalField(max_digits=10, decimal_places=2, default="0.0")
description = models.CharField(max_length=256, default=None, null=True)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(default=timezone.now)
:
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<div style="border: 1px solid">
<h3>aaaaaaaaaaa<span class="pull-right"><i class="glyphicon glyphicon-plus btn-flat"></i></span></h3>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12 text-center">
<div style="border: 1px solid">
<h3>bbbbbbbbbbb<span class="pull-right"><i class="glyphicon glyphicon-plus btn-flat"></i></span></h3>
</div>
</div>
</div>
</div>
所以这是我的问题。如何创建新的交易,按ID分配帐户和类别,然而在检索所有内容时,请带上所有详细信息?
答案 0 :(得分:0)
创建两个序列化程序,一个用于列表,一个用于创建,这就是诀窍。
class ListTransactionSerializer(serializers.ModelSerializer):
account = AccountSerializer()
category = CategorySerializer()
class Meta:
model = Transaction
fields = '__all__'
class CreateTransactionSerializer(serializers.ModelSerializer):
account = serializers.PrimaryKeyRelatedField(read_only=True)
category = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = Transaction
fields = '__all__'
def create(self, validated_data):
"""
Create and return a new 'Transaction' instance
:param validated_data:
:return: Transaction
"""
return Transaction.objects.create(**validated_data)
def update(self, instance, validated_data):
pass
答案 1 :(得分:-1)
首先将模型重写为相关名称文件以供其他实现。
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fileds = '__all__'
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fileds = '__all__'
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fileds = '__all__'
class SerializerTransactions(serializers.ModelSerializer):
user_serialzer = UserSerializer(many=True)
account_serialzer = AccountSerializer(many=True)
category_serialzer = CategorySerializer(many=True)
class Meta:
model = Transaction
fileds = ('id', 'name', 'user_serialzer', 'account_serialzer', 'category_serialzer',)
然后序列化器:
$date = new DateTime();
for( $days = 6; $days--; ) {
echo $date->modify( '+1 days' )->format( 'l' ) . '<br>';
}