jwjacobson / jazztunes

a jazz repertoire management app
https://jazztunes.org
GNU General Public License v3.0
4 stars 1 forks source link

Connect users to tunes via a ManyToMany field #31

Closed jwjacobson closed 11 months ago

jwjacobson commented 11 months ago

I assume this would be via its own model? Currently researching...

jwjacobson commented 11 months ago

It seems the standard way to do this is not via a discrete model but rather the Django ManyToMany field. I'll do that for now and leave open the question of how to later get datetime info into the field...

ryaustin commented 11 months ago

You are correct Jeff, many to many field is the way to go here What do you mean about getting datetime info into the field?

jwjacobson commented 11 months ago

I was assuming that Django would be connecting the User and Tune models via an intermediary entity (a UserTune table?) and I could use that to store the datetime when the tune was added to the repertoire as well as the datetime when it was last played. Now that I think about it, though, if we instead have the tune object never existing outside of a user's repertoire, these fields can just be part of Tune.

bbelderbos commented 11 months ago

Yeah the existing M2M field is great but only for simple relations, e.g. we used it for the tags on our exercises:

class Tag(models.Model):
    name = models.CharField(max_length=128)

...

class Bite(models.Model):
    tags = models.ManyToManyField(Tag, related_name='tags')

However if you need to store additional attributes on the M2M relation you better go with a new model, e.g. on our platform we have BiteConsumer which expresses the M2M relation between user and exercise, here is the reason:

class BiteConsumer(models.Model):
    bite = models.ForeignKey(Bite, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    completed = models.BooleanField(default=False)
    final_code = models.TextField(blank=True, null=True)
    user_level = models.IntegerField(blank=True, null=True)
...
many more attrs
...

We need to store many more things about this relation so we made our own model, the M2M field would not suffice here.

In this case all you need to do is making a new model class and point to the two related models via a ForeignKey field.

Makes sense?

bbelderbos commented 11 months ago

As discussed the 2nd approach makes more sense because you will have additional attributes to store on the M2M relation.