我正在尝试在包含连接表中的行的简单GET中返回JSON。模特:
class School(models.Model):
id = models.CharField(max_length=18,primary_key=True)
name = models.CharField(max_length=255,blank=False)
class Meta:
db_table='school'
class FKTable(models.Model):
school = models.ForeignKey(School,blank=False, db_column='school_id', on_delete=models.CASCADE)
name = models.CharField(max_length=45, blank=False)
value = models.CharField(max_length=255, blank=True, null=True)
class Meta:
db_table='fk_table'
序列化器:
class SchoolListSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='id')
name = serializers.CharField(source='name')
fkColumn = ????
class Meta:
model = models.School
fields = ('id','name','fkColumn')
问题是我还要在'name'列上过滤我加入的嵌套资源,所以我不知道在序列化程序中为'fkColumn'添加什么。在SQL中,它看起来像这样:
SELECT school.*, fk_table.value from school INNER JOIN fk_table on
fk_table.school_id = school.id AND fk_table.name = 'some name'
我想要的最终结果是:
{
"schools": [
{
"id": "someId",
"name": "someName",
"fkColumn": "Value"
}]}
RelatedField似乎不起作用,并且没有任何文档似乎给出了如何执行此操作的可靠答案。有什么想法吗?
答案 0 :(得分:0)
澄清后修改。定义fkeySerializer:
class fkeySerializer(serializers.ModelSerializer):
...
然后在主序列化程序中链接:
fkey = fkeySerializer(many=True)
class Meta:
model = models.School
fields = ('id','name','fkColumn',)
您可以在此处使用MethodField序列化程序。例如:
fkColumn = serializers.SerializerMethodField()
def get_fkColumn(self, obj):
return obj.fkColumn
class Meta:
model = models.School
fields = ('id','name','fkColumn',)
顺便说一下,也许有一个很好的理由,但重命名这个表可能更容易阅读