在 DRF 序列化程序中包含特定的外键
Include Specific Foreign Keys in DRF Serializer
这里有两个简单的模型作为示例:
class Author(models.Model):
name = models.CharField(blank=True, max_length=50)
age = models.IntegerField(null=True, )
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author)
date = models.DateField()
现在我想做的是为 Book
创建一个视图,使用 Django Rest Framework 从 Author
中提取其中一个值。这是一个例子 ModelSerializer
:
class BookMetaSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title','date','author__name',)
问题是不能像我上面给出的那样访问 DRF 中外键的字段 author__name
。我无法根据文档弄清楚如何执行此操作。感谢所有帮助,谢谢!
您可以使用source
参数定义author_name
字段来获取作者姓名。
上的 DRF 文档
The name of the attribute that will be used to populate the field. May
be a method that only takes a self
argument, such as
URLField('get_absolute_url')
, or may use dotted notation to traverse
attributes, such as EmailField(source='user.email')
.
最终代码:
class BookMetaSerializer(serializers.ModelSerializer):
# use dotted notation to traverse to 'name' attribute
author_name = serializers.CharField(source='author.name', read_only=True)
class Meta:
model = Book
fields = ('title','date','author_name',)
这里有两个简单的模型作为示例:
class Author(models.Model):
name = models.CharField(blank=True, max_length=50)
age = models.IntegerField(null=True, )
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author)
date = models.DateField()
现在我想做的是为 Book
创建一个视图,使用 Django Rest Framework 从 Author
中提取其中一个值。这是一个例子 ModelSerializer
:
class BookMetaSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title','date','author__name',)
问题是不能像我上面给出的那样访问 DRF 中外键的字段 author__name
。我无法根据文档弄清楚如何执行此操作。感谢所有帮助,谢谢!
您可以使用source
参数定义author_name
字段来获取作者姓名。
The name of the attribute that will be used to populate the field. May be a method that only takes a
self
argument, such asURLField('get_absolute_url')
, or may use dotted notation to traverse attributes, such asEmailField(source='user.email')
.
最终代码:
class BookMetaSerializer(serializers.ModelSerializer):
# use dotted notation to traverse to 'name' attribute
author_name = serializers.CharField(source='author.name', read_only=True)
class Meta:
model = Book
fields = ('title','date','author_name',)