我有这样的模型
class ProjectTemplate(models.Model):
project_template_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=64)
description = models.TextField(max_length=255)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
created_by = models.IntegerField(blank=True, null=True)
modified_by = models.IntegerField(blank=True, null=True)
activated = models.BooleanField(default=False)
org_id = models.IntegerField(blank=False,null=False)
class Meta:
db_table = 'project_template'
def __str__(self):
return self.name
和像这样的序列化程序类
class ProjectTemplateSerializer(serializers.ModelSerializer):
class Meta:
model = ProjectTemplate
在created_by字段中我将用户ID存储在数据库中,在列出项目模板时,基本上我将获得create_by字段的用户ID,
如何更改我的序列化程序类以获得这样的字典
{"user_id":id,"user_name":name}
for created_by field
答案 0 :(得分:0)
就像Sayse所说,你最好为这样的用户制作一个外键:
create_by = models.ForeignKey("User", related_name="project_user")
然后您可以通过以下方式访问用户的信息,例如user_name或其他内容:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("id", "user_name")
class ProjectTemplateSerializer(serializers.ModelSerializer):
user = UserSerializer(source="user", read_only=True)
class Meta:
model = ProjectTemplate
fields = (
"id", "user",
)