Reputation: 53
I'm building an app where i have a model linked to another via a many to many relationship. Here is an example: I have a sport training session, composed with multiple exercices, for example :
When i'm adding my exercices to my session, they are added in the front (angular) but when i refresh my page, only one copy of each exercice is kept in the session object.
Here are the models :
class Exercice(models.Model):
name = models.CharField(max_length=255)
class Session(models.Model):
sequences = models.ManyToManyField(Exercice, null=True, blank=True)
Any idea on how to have multiple times the same exercice in one Session ?
Upvotes: 0
Views: 51
Reputation: 1234
This is because the m2m will just contain the ids, not how many times you want them and the order.
It seems the issue is more related to your database structure.
Seems like you need a new table to store this information.
class Exercice(models.Model):
name = models.CharField(max_length=255)
class Session(models.Model):
exercices = models.ManyToManyField(Exercice, null=True, blank=True)
class Sequence(models.Model):
exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE)
session = models.ForeignKey(Session, on_delete=models.CASCADE)
#any extra info there
repetitions = models.PositiveSmallIntegerField(blank=True, null=True) #how many time each?
created_at = models.DateTimeField(auto_now_add=True) # used to generate the sequence of exercices
Then you can loop through this table to get what you want.
So in you backend when you create the session you should also create Sequence entry for each exercices you have within it
You can now access the sequence by looking at:
session = Session.objects.get(id=1#eg)
sequence = session.sequence_set.order_by('created_at')
Upvotes: 2
Reputation: 72
You are trying to create a type of history table not mapping actually. You can add a middleware model such below.
class ExerciseHistory(models.Model):
exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE)
session = models.ForeignKey(Session, on_delete=models.CASCADE)
created_date = models.DateTimeField(auto_now_add=True)
Upvotes: 1