Consider a soccer player (Player) and its position (Position) as an example.
In this case, ManyToMany comes into play.
Model example
class Position(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20, unique=True)
class Player(models.Model):
... (Omitted) ...
position = models.ManyToManyField(Position)
If you migrate Django using the above model definition, the following three tables will be created.
The table called player_position is the PK of the player table and the PK of the position table, and the information is managed as follows.
Extract all positions of the player "Pirlo"
positions = Player.objects.get(name='Pirlo').position.all()
[print(p.name) for p in positions]
Execution result:
DM
CM
Extract all players in the position of "CB" (Method 1)
players = Player.objects.filter(position=Position.objects.get(name='CB'))
[print(p.name) for p in players]
Execution result:
Maldini
Nesta
Extract all players in the position of "CB" (Method 2)
Model example (method 2)
class Player(models.Model):
... (Omitted) ...
position = models.ManyToManyField(Position, related_name='player')
players = Position.objects.get(name='CB').player.all()
[print(p.name) for p in players]
Execution result:
Maldini
Nesta
Method 1 and Method 2 extracted all the players in the position of "CB", but when I checked the created query, both generated the following SQL.
SELECT "soccer_player"."id", "soccer_player"."name", "soccer_player"."team_id"
FROM "soccer_player"
INNER JOIN "soccer_player_position" ON ("soccer_player"."id" = "soccer_player_position"."player_id")
WHERE "soccer_player_position"."position_id" = 1
Recommended Posts