Django Rest Framwork迭代模型序列化器中的字段 [英] django rest framwork iterate throug fields in model serializer
本文介绍了Django Rest Framwork迭代模型序列化器中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想遍历ModelSerializer中的字段,并希望使这些字段成为必填字段。这不起作用。我怎样才能做到这一点。
i want to iterate through the fields in ModelSerializer and want to make those field required . this not working . how can i do that. Somebody please help me.
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = Customer
fields = ("email", "phone_no", "full_name", "landline_no")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].required = True
self.fields[field].allow_blank = False
推荐答案
您可以在MetaSerializer的Meta类中添加额外的args,例如:
You can add the extra args in Meta class for a ModelSerializer, like this:
class Meta:
model = Customer
fields = ("email", "phone_no", "full_name", "landline_no")
extra_kwargs = {'email': {'required': True, 'allow_blank': False}}
如果所有字段都需要此字段,则应重新考虑字段中的字段客户
模型。您可以添加 blank = False
和/或 null = False
。在创建ModelSerializer时,Rest框架会将这些信息考虑在内
If you need this for all the fields, then you should reconsider your fields inside the Customer
model. You can add blank=False
and/or null=False
. Rest framework takes that information into consideration when creating a ModelSerializer
这篇关于Django Rest Framwork迭代模型序列化器中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文