当我在Django-Rest-Framework中获取嵌套数据时,我可以更改related_name吗?

时间:2017-12-26 12:27:01

标签: python django

比如我有两个模型,第一个是第二个iter_lines

ForeignKey

MyModelSerializer 中应该是:

class MyModel(models.Model):
    firstDate = models.DateTimeField(auto_now_add=True)
    another = models.CharField(max_length=30)

class MySubModel(models.Model):
    name = models.CharField(max_length=12)
    my_model = models.ForeignKey(to=MyModel, related_name="mysubs")

结果将如下:

class MyModelSerializer(ModelSerializer):
    mysubs = MySubModelSerializer(many=True, read_only=True)
    class Meta:
        model = MyModel
        fields = "__all__"

我想将密钥[ { "firstDate":xxxx, "another":xxxx, "mysubs":[ { "name":xxx, } ] } ] 替换为mysubs,是否可以这样做?

1 个答案:

答案 0 :(得分:0)

您可以使用source参数指定字段的来源:

children = MySubModelSerializer(many=True, read_only=True, source='mysubs')