运行Serializers.py提供了我想要的输出。问题出在ActivitiesSerializer类中,我必须覆盖化验字段,以便将其重命名为“ assays”以匹配db_table的名称。我不能在每种情况下都手动执行此操作。有什么方法可以覆盖默认的ModelSerializer来使用db_table名称而不是Foreignkey字段名称?
model.py:
class Activities(models.Model):
activity_id = models.BigIntegerField(primary_key=True)
assay = models.ForeignKey('Assays', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'activities'
class Assays(models.Model):
assay_id = models.BigIntegerField(primary_key=True)
doc = models.ForeignKey('Docs', models.DO_NOTHING)
class Meta:
managed = False
db_table = 'assays'
Serializers.py
class AssaysSerializer(serializers.ModelSerializer):
class Meta:
model = Assays
fields = '__all__'
depth = 0
class ActivitiesSerializer(serializers.ModelSerializer):
assays = AssaysSerializer(source='assay')
class Meta:
model = Activities
fields = '__all__'
depth = 0
ActivitiesObjectA = ActivitiesSerializer(Activities.objects.get(activity_id=17126237))
ActivitiesObjectA_JSON = JSONRenderer().render(ActivitiesObjectA.data)
print(ActivitiesObjectA_JSON)