通过非主键问题连接序列化器

时间:2019-04-16 21:05:48

标签: django django-rest-framework

我在创建项目和令牌之间的关系时遇到麻烦,我想在项目json结果中显示该项目的所有令牌。 项目的PK存储在Token的项目列中。

models.py

class Project(models.Model):
    name = models.CharField(max_length=50)

class Token(models.Model):
    project = models.ForeignKey(Project,on_delete=models.CASCADE,blank=True)
    symbol = models.CharField(max_length=50)

serializers.py

class TokenSerializer(serializers.ModelSerializer):
    allow_null=True
    class Meta:
        model = Token
        fields = ('id','symbol')

class ProjectSerializer(serializers.ModelSerializer):

    development = DevelopmentSerializer()
    tokens = TokenSerializer()

    class Meta:
        model = Project
        fields = ('id','name','tokens')

我想要的结果:

{
    "id": 1,
    "name": "Bitcoin",
    "tokens": [
        {
        "id": 1,
        "symbol": "BTC"
        }
    ]
}

这时出现以下错误:

尝试在序列化程序tokens上获取字段ProjectSerializer的值时出现AttributeError。序列化程序字段的名称可能不正确,并且与Project实例上的任何属性或键都不匹配。原始异常文本为:“项目”对象没有属性“令牌”。

1 个答案:

答案 0 :(得分:0)

You must add a related_name to your project field on model Token, so it works as a revers look-up:

class Token(models.Model):
    project = models.ForeignKey(Project,on_delete=models.CASCADE,blank=True, related_name='tokens')
    symbol = models.CharField(max_length=50)