【发布时间】:2021-06-21 23:28:57
【问题描述】:
我设置了一个序列化程序,它能够动态序列化 Django Rest Framework 文档中指定的所需字段。
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
>>> class UserSerializer(DynamicFieldsModelSerializer):
>>> class Meta:
>>> model = User
>>> fields = ['id', 'username', 'email']
>>>
>>> print(UserSerializer(user))
{'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'}
>>>
>>> print(UserSerializer(user, fields=('id', 'email')))
{'id': 2, 'email': 'jon@example.com'}
然后我将如何添加一个与 ForeignKey 相关的模型并动态序列化该模型中的所需字段?
我们可以制作模型
class User(models.Model):
id = IntegerField()
username = CharField()
email = EmailField()
class Vehicle(models.Model):
color = CharField()
type = CharField
year = DateField()
driver = ForeignKey(User)
然后根据视图包括颜色、类型、年份或这些的任意组合。
我想要这样的东西。
{
'id': 27,
'username': 'testuser',
'vehicle: {
'color': 'Blue',
'type': 'Truck',
}
}
【问题讨论】:
-
一种方法是覆盖
ModelSerializer的build_nested_field,但是您必须找到一种方法让该方法知道您要自定义哪个字段,以及您要动态设置的字段对于该字段的嵌套序列化程序。也许使用context?
标签: django django-models django-rest-framework django-serializer