gpt4 book ai didi

python - Django:获取要在 Angular 中显示的外键数据

转载 作者:行者123 更新时间:2023-11-29 16:12:42 25 4
gpt4 key购买 nike

我正在尝试通过外键关系检索表的所有列,并且想知道如何执行此操作。我有以下代码:

models.py

class Athletes(models.Model):
athlete_id = models.AutoField(db_column="AthleteID", primary_key="True")
first_name = models.CharField(db_column='FirstName', max_length=100)
last_name = models.CharField(db_column='LastName', max_length=100)

def __str__(self):
return str(self.athlete_id) + ' ' + self.first_name + ' ' + self.last_name

class Meta:
managed = True
db_table = 'Athletes'
ordering = ('athlete_id', )

class VelocityLoadPredict(models.Model):
vl_predict_id = models.AutoField(db_column="vl_predict_id", primary_key="True")
athlete_id = models.ForeignKey(Athletes, on_delete=models.CASCADE, db_column="athleteID")
lift_name = models.CharField(db_column="LiftName", max_length=100)

def __str__(self):
return str(self.vl_predict_id)

class Meta:
managed = True
db_table = 'velocity_load_predict'
ordering = ('vl_predict_id', )

我正在使用序列化器:

class AthletesSerializer(serializers.ModelSerializer):
class Meta:
model = Athletes
fields = ('athlete_id', 'first_name', 'last_name')

class VelocityLoadPredictSerializer(serializers.ModelSerializer):
class Meta:
model = VelocityLoadPredict
fields = ('vl_predict_id', 'athlete_id', 'lift_name')

在 Angular 中,我有以下代码(api.service):

analytics.component.ts

  analytics: Analytics[];  constructor(private data: DataService,
private api: ApiService) {
this.getAnalytics();
}
getAnalytics = () => {
this.api.getAnalytics().subscribe(
data => {
this.analytics = data;
},
error => {
console.log(error);
}
);

然后我想在我的 html 分析文件中表示名字、姓氏和电梯名称:

<p *ngFor='let element of analytics'>{{element.first_name}}</p>

当 Athletes 表通过 athlete_id 外键链接时,我该如何执行此操作?

谢谢!

更新:

如何使用 Angular 来代表运动员.first_name?

api.service.ts

  getVlPredict(): Observable<any> {
return this.http.get(this.baseurl + '/velocityloadpredict/',
{headers: this.httpHeaders});

}

analytics.component.ts

    vlpredict: string[] = [];

workoutCalls: string[] = ['first_name', 'lift_name'];
workoutNames: string[] = ['First Name', 'Lift Name'];

constructor(private data: DataService,
private api: ApiService) {
this.getVlPredict();
}

getVlPredict = () => {
this.api.getVlPredict().subscribe(
data => {
this.vlpredict = data;
},
error => {
console.log(error);
}
);
}

analytics.component.html

<div>
<mat-table [dataSource]="vlpredict" class="mat-elevation-z8" matSort>
<ng-container matColumnDef="{{column}}" *ngFor="let column of workoutCalls; index as i">
<mat-header-cell *matHeaderCellDef mat-sort-header>{{workoutNames[i]}}</mat-header-cell>
<mat-cell *matCellDef="let element">{{element[column]}}</mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="workoutCalls"></mat-header-row>
<mat-row *matRowDef="let row; columns: workoutCalls"></mat-row>
</mat-table>
</div>

最佳答案

您可以在 VelocityLoadPredictSerializer 中使用子序列化器

class VelocityLoadPredictSerializer(serializers.ModelSerializer):
athlete = AthletesSerializer() # this is sub serializer

class Meta:
model = VelocityLoadPredict
fields = ('vl_predict_id', 'athlete_id', 'lift_name', 'athlete')

然后你就可以得到这个。

{
"vl_predict_id": 1,
"lift_name": "blabla",
"athlete": {
"athlete_id": 2,
"first_name": "blabla",
"last_name": "blabla"
},
...
}

或者您只需要first_name,您可以使用source

class VelocityLoadPredictSerializer(serializers.ModelSerializer):
first_name = serializers.CharField(source='athlete.first_name')

class Meta:
model = VelocityLoadPredict
fields = ('vl_predict_id', 'athlete_id', 'lift_name', 'first_name')

那么,

{
"vl_predict_id": 1,
"lift_name": "blabla",
"first_name": "blabla",
...
}

如果您有更多信息,请参阅 Django Rest Framework sourcerelation

关于python - Django:获取要在 Angular 中显示的外键数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55112721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com