Good morning everybody!
I've a problem with django REST ModelSerializer.
This is my serializer:
class TransactionPayOutSerializer(serializers.ModelSerializer):
author = serializers.SlugRelatedField(queryset=Users.objects.all(), slug_field='unique_id', allow_null=True)
wallet = serializers.SlugRelatedField(queryset=Wallet.objects.all(), slug_field='wallet_id')
bank_account = serializers.SlugRelatedField(queryset=BankAccount.objects.all(), slug_field='bank_account_id')
class Meta:
model = PayOut
fields = ('author', 'wallet', 'amount',
'currency', 'bank_account')
def __init__(self, **kwargs):
if 'instance' in kwargs:
super(TransactionPayOutSerializer,self).__init__(kwargs.get('instance'))
else:
self.merchant = kwargs.pop('merchant')
super(TransactionPayOutSerializer, self).__init__(**kwargs)
def validate(self, data):
print 'Inside serializer validate(), data:'
print data
wallet = data['wallet']
user_wallet = UserWallets.objects.get(wallet=wallet)
if self.merchant != user_wallet.merchant:
raise serializers.ValidationError("Wallet not found")
wallet.fetch()
if wallet.balance < data['amount']:
raise serializers.ValidationError("Not enough founds in wallet")
return data
def create(self, validated_data):
print 'Inside TransactionPayOutSerializer create():'
print 'Validated data:'
print validated_data
pay_out = PayOut(**validated_data)
user_wallet = UserWallets.objects.get(wallet=validated_data['wallet'])
pay_out.author = user_wallet.user
pay_out.merchant = self.merchant
pay_out.save()
return pay_out
It works perfectly but my problem is:
When the serializer is used for a get request (serializer.data) it's perfect. But when the serializer is used for a post request (TransactionPayOutSerializer(data=request.DATA)) it absolutely wants the 'user' parameter in the JSON. What is the best way to keep serialzer.data return 'user' representation making TransactionPayOutSerializer(data=request.DATA) works without receiving 'user' as parameter inside JSON post request? I should use simple serializers instead of ModelSerializers?
Thanks in advance!