Django序列化正向查询只能取一个字段值吗?
有文章和用户两个表,文章表关联了用户表。
文章表
class Articles(BaseModel): """文章表"""
title = models.CharField(max_length=100, verbose_name='标题')
# 关联作者
authors = models.ForeignKey(to=Authors, on_delete=models.CASCADE, verbose_name='提问者', related_name='a_article')
...
用户表
class Authors(BaseModel): """前段作者表"""
name = models.CharField(max_length=32, verbose_name='名称')
avatar = models.CharField(max_length=255, verbose_name='头像地址')
SEX_CHOICES = (
('0', '女'),
('1', '男'),
('3', '保密')
)
sex = models.CharField(max_length=1, choices=SEX_CHOICES, default=3, verbose_name='性别', null=True, blank=True)
...
用户序列化器:
class AuthorsSerializer(serializers.ModelSerializer): """用户"""
class Meta:
model = models.Authors
fields = ('id', 'name', 'avatar')
文章正向查询用户表
序列化关联查询,source只能取一个字段吗?
class ArticlesSerializer(serializers.ModelSerializer): """文章"""
author = serializers.CharField(source='authors.id')
class Meta:
model = models.Articles
fields = ('id', 'title', 'browse', 'is_success', 'types', 'author')
source='authors.id' 只能查询一个字段,无法同时获取用户的id,name,avatar
回答:
直接用的你创建好了的 AuthorsSerializer 就行了,按照你提供的代码来看可以参考下面;
class ArticlesSerializer(serializers.ModelSerializer): author = AuthorsSerializer(source="authors", many=False)
class Meta:
model = models.Articles
fields = fields = (
'id', 'title', 'browse', 'is_success', 'types', 'author'
)
以上是 Django序列化正向查询只能取一个字段值吗? 的全部内容, 来源链接: utcz.com/p/938598.html