Django Rest 框架,如何在 ModelSerializer 中包含“__all__"字段和相关字段? [英] Django Rest framework, how to include '__all__' fields and a related field in ModelSerializer ?
问题描述
我有两种模型,一种具有 M2M 关系和相关名称.我想在序列化程序和相关字段中包含所有字段.
I have two models, one with M2M relation and a related name. I want to include all fields in the serializer and the related field.
models.py:
class Pizza(models.Model):
name = models.CharField(max_length=50, unique=True)
toppings = models.ManyToManyField(Topping, null=True, blank=True, related_name='pizzas')
class Topping(models.Model):
name = models.CharField(max_length=50, unique=True)
price = models.IntegerField(default=0)
serializer.py:
serializer.py:
class ToppingSerializer(serializers.ModelSerializer):
class Meta:
model = Topping
fields = '__all__'
这有效,但不包括相关字段.
This works but it doesn't include the related field.
fields = ['name', 'price', 'pizzas']
这完全符合我的要求,但是当 Toppings 模型有很多字段时会发生什么.我想做类似的事情:
This works exactly as I want, but what happens when Toppings model has a lot of fields. I want to do something like :
fields = ['__all__', 'pizzas']
此语法导致错误提示:
字段名称 __all__
对模型无效
Field name
__all__
is not valid for model
有没有办法实现想要的行为?还是在使用相关名称时必须手动输入字段?
Is there a way to achieve the wanted behavior? Or the fields must be typed manually when using a related name ?
推荐答案
我刚刚查看了 Django Rest Framework 的源代码.框架似乎不支持您想要的行为.
I just checked the source code of Django Rest Framework. The behaviour you want seems not to be supported in the Framework.
fields
选项必须是列表、元组或文本 __all__
.
The fields
option must be a list, a tuple or the text __all__
.
以下是相关源代码的片段:
Here is a snippet of the relevant source code:
ALL_FIELDS = '__all__'
if fields and fields != ALL_FIELDS and not isinstance(fields, (list, tuple)):
raise TypeError(
'The `fields` option must be a list or tuple or "__all__". '
'Got %s.' % type(fields).__name__
)
您不能将all"附加到包含字段的元组或列表中...
You cannot add 'all' additionally to the tuple or list with fields...
这篇关于Django Rest 框架,如何在 ModelSerializer 中包含“__all__"字段和相关字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!