Django:获取外键数据以在Angular中显示

时间:2019-03-12 01:15:27

标签: python mysql django angular foreign-keys

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

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>

当运动员表通过athlete_id的外键链接时,我该怎么做?

谢谢!

更新:

如何与Angular一起代表运动者的名字?

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>

1 个答案:

答案 0 :(得分:0)

您可以在sub serializer中使用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