Django
Relaciones de muchos a muchos
Buscar..
Con un modelo pasante.
class Skill(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
class Developer(models.Model):
name = models.CharField(max_length=50)
skills = models.ManyToManyField(Skill, through='DeveloperSkill')
class DeveloperSkill(models.Model):
"""Developer skills with respective ability and experience."""
class Meta:
order_with_respect_to = 'developer'
"""Sort skills per developer so that he can choose which
skills to display on top for instance.
"""
unique_together = [
('developer', 'skill'),
]
"""It's recommended that a together unique index be created on
`(developer,skill)`. This is especially useful if your database is
being access/modified from outside django. You will find that such an
index is created by django when an explicit through model is not
being used.
"""
ABILITY_CHOICES = [
(1, "Beginner"),
(2, "Accustomed"),
(3, "Intermediate"),
(4, "Strong knowledge"),
(5, "Expert"),
]
developer = models.ForeignKey(Developer, models.CASCADE)
skill = models.ForeignKey(Skill, models.CASCADE)
"""The many-to-many relation between both models is made by the
above two foreign keys.
Other fields (below) store information about the relation itself.
"""
ability = models.PositiveSmallIntegerField(choices=ABILITY_CHOICES)
experience = models.PositiveSmallIntegerField(help_text="Years of experience.")
Se recomienda que se cree un índice único en conjunto (developer,skill)
. Esto es especialmente útil si se está accediendo / modificando su base de datos desde fuera de django. Encontrará que dicho índice es creado por django cuando no se está utilizando un modelo explícito a través de.
Simple muchos a muchos relación.
class Person(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
class Club(models.Model):
name = models.CharField(max_length=50)
members = models.ManyToManyField(Person)
Aquí definimos una relación donde un club tiene muchas Person
y miembros y una Persona puede ser miembro de varios Club
diferentes.
Aunque solo definimos dos modelos, django crea tres tablas en la base de datos para nosotros. Estas son myapp_person
, myapp_club
y myapp_club_members. Django crea automáticamente un índice único en las myapp_club_members(club_id,person_id)
.
Uso de muchos campos de muchos
Usamos este modelo del primer ejemplo:
class Person(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
class Club(models.Model):
name = models.CharField(max_length=50)
members = models.ManyToManyField(Person)
Agrega a Tom y Bill al club nocturno:
tom = Person.objects.create(name="Tom", description="A nice guy")
bill = Person.objects.create(name="Bill", description="Good dancer")
nightclub = Club.objects.create(name="The Saturday Night Club")
nightclub.members.add(tom, bill)
Quien esta en el club
for person in nightclub.members.all():
print(person.name)
Te regalaré
Tom
Bill