0

生のSQLだけに頼らずに、Djangoで次のSQL結合ステートメントを実行する方法を理解しようとしています。それを行う方法はありますか?

Select * from playertable, seasontable where player.id = season.player_id

これが私のモデルです。明確にするために、上記のクエリでは省略されたテーブル名を使用して明確にしました

class Player(models.Model): 
    name = models.CharField(max_length=200)
    team = models.CharField(max_length=3)
    position = models.CharField(max_length=3)

class PlayerSeason(models.Model):

    player = models.ForeignKey(Player)
    year = models.IntegerField()
    games_played = models.IntegerField()
    goals = models.IntegerField()
    assists = models.IntegerField()
    points = models.IntegerField()
    plusminus = models.CharField(max_length=200)
    pim = models.IntegerField()
    ppg = models.IntegerField()
    shg = models.IntegerField()
    gwg = models.IntegerField()
    otg = models.IntegerField()
    shots = models.IntegerField()
    shooting_percentage = models.DecimalField(max_digits=5, decimal_places=2)
    toi = models.CharField(max_length=200)
    sftg = models.DecimalField(max_digits=5, decimal_places=2)
    face_off = models.DecimalField(max_digits=5, decimal_places=2)

Djangoでこれをどのように行う必要がありQuerySetますか?

4

2 に答える 2

1

特定のシーズンに関連付けられているすべてのプレーヤーを取得することだけが必要な場合は、Djangoの後方関係を利用できます。

モデル(この場合はSeason)に対してForeignKeyFieldを使用すると、そのモデルインスタンスは、関連するすべてのオブジェクトのクエリセットを取得できる属性を取得します。

あなたの例では、を使用できますseason.player_set.all()

シーズン属性の名前を変更できるオプションのパラメータrelated_nameをに渡すことができます。ForeignKeyField

于 2013-01-17T18:28:08.783 に答える
-1

それを行う方法はありますか?

いいえ。DjangoのORMは一度に1つのモデルを処理し、2つのテーブルから列を取得しています。いずれかのモデルでクエリを実行してから、適切なフィールドにアクセスして、関連するモデルを取得します。

于 2013-01-17T16:43:32.583 に答える