我对Django Rest Framework上的序列化程序有疑问......首先我的模型是:
class Transaction(Model):
type_choices = (
(1, 'deposit'),
(2, 'withdrawal')
)
status_choices = (
(1, 'pending'),
(2, 'made'),
(3, 'canceled'),
(4, 'completed')
)
name = CharField(null=True, blank=True,max_length=50,)
description = TextField(null=True, blank=True)
amount = FloatField()
type = IntegerField(choices=type_choices, )
status = IntegerField(choices=status_choices, )
client = ForeignKey(User, related_name='transaction_client', blank=True, null=True)
cards = ManyToManyField(Card, through='TransactionCard')
created_by = ForeignKey(User, related_name='transaction_created_by')
created_at = DateTimeField(auto_now_add=True, editable=False)
updated_by = ForeignKey(User, null=True, related_name='transaction_updated_by')
updated_at = DateTimeField(auto_now=True, editable=False)
class Meta:
ordering = ('-created_at',)
def __str__(self):
return self.name
class TransactionCard(Model):
transaction = ForeignKey(Transaction, related_name='transactioncard_transaction')
card = ForeignKey(Card, related_name='transactioncard_card')
amount = FloatField()
class Card(Model):
name = CharField(null=True, blank=True, max_length=100,)
description = TextField(null=True, blank=True,)
card_number = TextField(max_length=16, )
month_exp = IntegerField()
year_exp = IntegerField()
month_acq = IntegerField(null=True, blank=True,)
year_acq = IntegerField(null=True, blank=True, )
card_type = ForeignKey(CardType, related_name='cards_card_type')
provider = ForeignKey(Provider, related_name='cards_provider')
balance = FloatField()
active = BooleanField()
created_by = ForeignKey(User, related_name='cards_created_by')
created_at = DateTimeField(auto_now_add=True, editable=False)
updated_by = ForeignKey(User, null=True, related_name='cards_updated_by')
updated_at = DateTimeField(auto_now=True, editable=False)
class Meta:
ordering = ('month_exp', 'year_exp',)
def __str__(self):
return self.name
我的序列化器是:
class TransactionCreateSerializer(ModelSerializer):
created_by = StringRelatedField()
updated_by = StringRelatedField()
class Meta:
model = Transaction
fields = [
'id',
'name',
'description',
'amount',
'type',
'status',
'client',
'cards',
'created_by',
'created_at',
'updated_by',
'updated_at'
]
extra_kwargs = {
'created_by': {
'read_only': True
},
'updated_by': {
'read_only': True
}
}
def create(self, validated_data):
pprint(validated_data.pop('cards'))
transaction = Transaction.objects.create(**validated_data)
return transaction
我的问题是,当我尝试将validated_data.pop(卡片)设置为错误时,我不知道为什么会这样做。
更新
它的错误:
pprint(validated_data.pop('cards))
KeyError: 'cards'