Django Rest框架,如何在ModelSerializer中包括'__all__'字段和相关字段? [英] Django Rest framework, how to include '__all__' fields and a related field in ModelSerializer ?

查看:362
本文介绍了Django Rest框架,如何在ModelSerializer中包括'__all__'字段和相关字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,一个具有M2M关系,一个具有相关名称。我想在序列化程序和相关字段中包括 all 字段。

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:

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 __ 对模型无效

有没有办法实现想要的行为?还是在使用相关名称时必须手动键入字段?

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.

字段选项必须为列表,元组或文本 __ 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__
        )

您不能在元组或列表中另外添加 全部有字段...

You cannot add 'all' additionally to the tuple or list with fields...

这篇关于Django Rest框架,如何在ModelSerializer中包括'__all__'字段和相关字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆